﻿Imports System.Data.OleDb
Imports System.Drawing.Imaging
Imports System.IO
Imports System.IO.File
Imports System.IO.Ports
Imports System.Math
Imports System.Net
Imports System.Net.Sockets
Imports System.Text
Imports System.Threading
Imports System.Xml
Imports Cognex.VisionPro
Imports Cognex.VisionPro.Barcode
Imports Cognex.VisionPro.CalibFix
Imports CommonJson
Imports HslCommunication
Imports HslCommunication.Profinet.Melsec
Imports NCHQMES

Public Class FrmMain
    Dim pset1 As Boolean
    Dim pset2 As Boolean
    Dim pset3 As Boolean
    Dim pset4 As Boolean
    Dim pget1 As Boolean
    Dim pget2 As Boolean
    Dim pget3 As Boolean
    Dim pget4 As Boolean

    Public pointCAD(68) As Double
    Public pointCAD_Z(30) As Double
    Public pointCAD_C(30) As Double
    Public pointCAD_FLG1(30) As Double
    Public resu(60) As Double   'twopointurn 函数返回XY转数组
    Public temp(10) As Double
    Public bzw As Integer
    Public tempx(10) As Double
    Public photo_point(12) As Double

    Dim IsScrewFail As Boolean = False
    Dim Rate0 As Double = 511 / 659 '图像与现实框比例
    Dim myGraphics As Graphics
    Dim bm As Bitmap
    Dim picRatio As Double
    Dim wait_NO As Integer = 0
    Dim UPloadTime As Double = 0

#Region "菜单命令"

    Private _left As String
    Private _right As String
    Private _strConv As String

    Private Property Left(ByVal p1 As String, ByVal p2 As Integer) As String
        Get
            Return _left
        End Get
        Set(ByVal value As String)
            _left = value
        End Set
    End Property

    Private Property Right(ByVal p1 As String, ByVal p2 As Integer) As String
        Get
            Return _right
        End Get
        Set(ByVal value As String)
            _right = value
        End Set
    End Property

    Private Sub 关于本程序ToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles 关于本程序ToolStripMenuItem.Click
        FrmAbout.ShowDialog()
    End Sub

    Private Sub 产品管理ProductToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles 产品管理ProductToolStripMenuItem.Click
        FrmProduct.ShowDialog()
    End Sub

    Private Sub 登陆LoginToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles 登陆LoginToolStripMenuItem.Click
        If gPriority = 0 Then
            FrmAdmin.ShowDialog()
        Else
            MsgBox("人员已登陆, 请先登出!")
        End If

    End Sub

    Private Sub 登出LogoutToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles 登出LogoutToolStripMenuItem.Click
        gPriority = 0
        DataByPCS.OperatorID = ""
        TextBox_OPID.Text = "未登录"
        TextBox_OPID.BackColor = Color.WhiteSmoke
        FrmAdmin.EnableMenu()
    End Sub

    Private Sub 参数设置ToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles 参数设置ToolStripMenuItem.Click
        ParameterSet.ShowDialog()
    End Sub

    Private Sub 退出ExitToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles 退出ExitToolStripMenuItem.Click
        AppendInfoToTextBox("点击了退出")
        Process.GetCurrentProcess().Kill()
        Me.Close()
    End Sub

#End Region

#Region "初始化"

    Public m_devicenotify As DeviceNotify
    Dim DevicePath As String '全局变量，储存加密锁所在的路径
    Public Const ErrMsg As String = "未能找到指定的软件授权，请联系供应商咨询！"

    Dim m_aryClients As New ArrayList
    Dim mServer As Socket
    Dim mServer1 As Socket
    Dim mServer2 As Socket
    Dim mServer3 As Socket
    Dim mServer4 As Socket
    Dim mServer5 As Socket
    Dim mServer6 As Socket
    Dim mServer7 As Socket
    Dim mServer8 As Socket
    Dim mServer9 As Socket
    Dim mServer10 As Socket
    Dim mServer11 As Socket
    Dim mServer12 As Socket
    Dim mServer13 As Socket
    Dim mServer14 As Socket
    Dim mServer15 As Socket
    Dim mServer16 As Socket

    Delegate Sub AddClientToList(ByVal strName As String)

    Delegate Sub AddRecvToText(ByVal strName As String)

    Delegate Sub ShowAlarmFrm(ByVal strName As String)

    Delegate Sub DeletClientFromList(ByVal strName As String)

    Delegate Sub OpenTimer()

    Delegate Sub UseAxM(ByVal strName As String)

    Private Function GetXML()
        Dim xmlpath = UploadPath & "\Param.xml"
        If Exists(xmlpath) Then
            Dim xtr As XmlTextReader = New XmlTextReader(xmlpath)
            Try
                While xtr.Read()
                    If xtr.NodeType = XmlNodeType.Element And xtr.LocalName = "FTPUploadPath" Then
                        FTPUploadPath1 = xtr.ReadString()
                    End If
                    If xtr.NodeType = XmlNodeType.Element And xtr.LocalName = "MySQLIP" Then
                        MySQLIP = xtr.ReadString()
                    End If
                    If xtr.NodeType = XmlNodeType.Element And xtr.LocalName = "MySQLUserName" Then
                        MySQLUserName = xtr.ReadString()
                    End If
                    If xtr.NodeType = XmlNodeType.Element And xtr.LocalName = "MySQLPwd" Then
                        MySQLPassWord = xtr.ReadString()
                    End If
                    If xtr.NodeType = XmlNodeType.Element And xtr.LocalName = "MySQLDB" Then
                        MySQLDataBase = xtr.ReadString()
                    End If

                End While
            Catch ex As Exception
                MsgBox("参数文件读取错误!" & vbCrLf & ex.Message.ToString)
            Finally
                xtr.Close()
            End Try
        End If
    End Function

    Public Sub InitMachineInfo()
        Dim xmlpath = Application.StartupPath & "\MachineInfo.xml"
        If Exists(xmlpath) Then
            Dim xtr As XmlTextReader = New XmlTextReader(xmlpath)
            Try
                While xtr.Read()
                    If xtr.NodeType = XmlNodeType.Element And xtr.LocalName = "DeviceType" Then
                        machineInfo.Device_type = xtr.ReadString()
                    End If
                    If xtr.NodeType = XmlNodeType.Element And xtr.LocalName = "Manufacturer" Then
                        machineInfo.Manufacturer = xtr.ReadString()
                    End If
                    If xtr.NodeType = XmlNodeType.Element And xtr.LocalName = "DeviceCode" Then
                        machineInfo.Device_Code = xtr.ReadString()
                    End If
                    If xtr.NodeType = XmlNodeType.Element And xtr.LocalName = "DeviceId" Then
                        machineInfo.Device_id = xtr.ReadString()
                    End If
                    If xtr.NodeType = XmlNodeType.Element And xtr.LocalName = "Line" Then
                        machineInfo.Line = xtr.ReadString()
                    End If
                    If xtr.NodeType = XmlNodeType.Element And xtr.LocalName = "IP" Then
                        machineInfo.IP = xtr.ReadString()
                    End If
                    If xtr.NodeType = XmlNodeType.Element And xtr.LocalName = "Station" Then
                        machineInfo.Station = xtr.ReadString()
                    End If
                    If xtr.NodeType = XmlNodeType.Element And xtr.LocalName = "Fixture" Then
                        machineInfo.Fixture = xtr.ReadString()
                    End If
                    If xtr.NodeType = XmlNodeType.Element And xtr.LocalName = "Family" Then
                        machineInfo.Family = xtr.ReadString()
                    End If
                    If xtr.NodeType = XmlNodeType.Element And xtr.LocalName = "StateFre" Then
                        StateFreTime = xtr.ReadString()
                        UploadStatus.Interval = StateFreTime * 1000

                    End If
                    If xtr.NodeType = XmlNodeType.Element And xtr.LocalName = "ProductFre" Then
                        ProductFreTime = xtr.ReadString()
                        'UploadMainInfo.Interval = ProductFreTime * 1000

                    End If
                End While
                machineInfoStatus.Device_type = machineInfo.Device_type
                machineInfoStatus.Manufacturer = machineInfo.Manufacturer
                machineInfoStatus.Device_Code = machineInfo.Device_Code
                machineInfoStatus.Device_id = machineInfo.Device_id
                machineInfoStatus.Line = machineInfo.Line
                machineInfoStatus.IP = machineInfo.IP
                mainInfo.Device_id = machineInfo.Device_id
                mainInfo.Line = machineInfo.Line
                SNInfo.Device_id = machineInfo.Device_id
                SNInfo.Line = machineInfo.Line
                SNInfo.Family = machineInfo.Family
            Catch ex As Exception
                MsgBox("设备信息文件错误!" & vbCrLf & ex.Message.ToString)
            Finally
                xtr.Close()
            End Try
        End If

    End Sub

    Public Sub initkey() '初始化加密狗
        Dim ret As Integer
        '这个用于判断系统中是否存在着加密锁。不需要是指定的加密锁,
        DevicePath = ""

        If FindPort(0, DevicePath) <> 0 Then
            MessageBox.Show(ErrMsg)
            End
        End If
        '注册加密锁事件插拨通知
        m_devicenotify = New DeviceNotify()

        '使用普通加密算法进行加密
        If (CheckKeyByFindort_2() <> 0) Then
            MessageBox.Show(ErrMsg, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error)
            End
        End If
        '使用储存器进行加密

        ret = CheckKeyByReadEprom()
        If (ret = 1) Then
            MessageBox.Show("你生成加密代码时没有设置该函数", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information)
            End
        End If
        If (ret <> 0) Then
            MessageBox.Show(ErrMsg, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error)
            End
        End If
        '增强算法

        ret = CheckKeyByEncstring()
        If (ret = 1) Then
            MessageBox.Show("你生成加密代码时没有设置该函数", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information)
            End
        End If
        If (ret <> 0) Then
            MessageBox.Show(ErrMsg, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error)
            End
        End If

    End Sub

    Public Sub initTool() '初始化使用的工具
        Try
            Dim filePath As String
            TSProcessLoad.Value = 0
            filePath = DebugPath & "\tool\"
            'MsgBox(filePath)
            For i = 0 To Cam_num - 1
                gTBCheck(i) = New CogToolBlock
                fifo(i) = New CogAcqFifoTool
            Next
            For i = 0 To Cam_num - 1
                gTBCheck(i) = CogSerializer.LoadObjectFromFile(filePath & "TBCheck" & (i + 1).ToString & ".vpp")
                gTBCheck(i).LastRunRecordEnable = Cognex.VisionPro.Implementation.Internal.CogUserToolLastRunRecordConstants.CompositeSubToolRecords
                fifo(i) = gTBCheck(i).Tools.Item("相机设定")
            Next
        Catch ex As Exception
            MsgBox("初始化图像处理参数失败!" & ex.Message)
        End Try

    End Sub

    Public Sub InitIO() '初始化IO卡
        Try
            gIOCard = Register_Card(PCI_7230, 0)
            If (gIOCard) < 0 Then
                MsgBox("IO卡初始化失败！")
            End If
        Catch ex As Exception
            MsgBox("初始化IO卡和其他驱动卡失败!" & ex.Message)
        End Try
    End Sub

    Public Sub InitCom() '初始化通讯相关
        Try
            If SP1.IsOpen Then
                SP1.Close()
            End If
            SP1.PortName = "COM1"
            SP1.BaudRate = 9600
            SP1.DataBits = 8
            SP1.StopBits = IO.Ports.StopBits.One
            SP1.Open()

            If SP1.IsOpen Then
                COM2_ZT.Text = "连接"
                Timer4.Enabled = True
                COM2_ZT.BackColor = Color.Lime
            Else
                COM2_ZT.Text = "断开"
                Timer4.Enabled = False
                COM2_ZT.BackColor = Color.Red
            End If
            Dim filepath = DebugPath & "\Tool\"
            Dim JQSN As Boolean = Exists(filepath & "\JQGZ.txt")
            If JQSN Then
                Dim startDly1 As Integer = FreeFile()
                FileOpen(startDly1, filepath & "\JQGZ.txt", OpenMode.Random)
                FileGet(startDly1, JQStart)
                FileGet(startDly1, JQLength)
                FileClose(startDly1)
            End If
        Catch ex As Exception
            COM2_ZT.Text = "断开"
            COM2_ZT.BackColor = Color.Red
            AppendInfoToTextBox("初始化IO卡和其他驱动卡失败!" & ex.Message)
            'MsgBox("初始化IO卡和其他驱动卡失败!" & ex.Message)
        End Try
    End Sub

    Private Sub InitCam() '初始化相机
        Try
        Catch ex As Exception
            MsgBox("相机初始化错误！")
        End Try
    End Sub

#Region "扫码接收"

    Public Function SendData(ByVal data As String, ByVal servIP As String, ByVal portNO As String) As String
        Dim str As String = ""
        Dim mySocket As Socket = New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)
        Try
            Dim connResult As IAsyncResult = mySocket.BeginConnect(servIP, portNO, Nothing, Nothing)
            connResult.AsyncWaitHandle.WaitOne(2000, False) '  //等待2秒
            If connResult.IsCompleted = False Then
                mySocket.Close()
                str = "与" & servIP & ":" & portNO & "的连接超时"
            Else
                mySocket.Send(Encoding.GetEncoding("GB2312").GetBytes(data))
                Threading.Thread.Sleep(100)
                mySocket.Close()
            End If
        Catch ex As Exception
            mySocket.Close()
            str = ex.Message.ToString & ex.StackTrace.ToString
        End Try
        Return str
    End Function

    'Public Sub InitTcpSever2() '初始化TCP服务器
    '    Dim mServer2(0) As Socket
    '    Dim IP2 As String = "192.168.2.100"
    '    Dim Port2 As Integer = 9000
    '    socket2 = New SocketHelper
    '    Try
    '        socket2.InitTcpSever(mServer2, IP2, Port2)
    '        Dim receive As SocketReceiveData = New SocketReceiveData(AddressOf RecevDataProcess2)
    '        socket2.InitSocketReceiveData(receive)
    '    Catch ex As Exception
    '        MsgBox("InitTcpSever:" & ex.Message.ToString & ex.StackTrace.ToString)
    '        AddErrMsgToTextBox(Format(DateAndTime.Now, "yyyy-MM-dd HH:mm:ss") & ex.Message.ToString() & "待分析" & "咨询生产厂商" & "软件故障")

    '    End Try
    'End Sub

#Region "增加USB转网口程序"

    Public Sub InitTcpSever2()

        Dim aryLocalAddr As IPAddress()
        Dim strHostName As String
        Dim mmServer(0) As Socket

        newsetM(0) = False
        newsetM(1) = False
        newsetM(2) = False
        newsetM(3) = False
        newsetM(4) = False
        newsetM(5) = False

        Try
            strHostName = Dns.GetHostName()  '获取本地计算机的主机名
            Dim ipEntry As IPHostEntry = Dns.GetHostByName(strHostName)  '获取指定 DNS 主机名的 DNS 信息  IPHostEntry(为 Internet 主机地址信息提供容器类)
            aryLocalAddr = ipEntry.AddressList  '获取与主机关联的 IP 地址列表
            For I As Integer = 0 To aryLocalAddr.Length - 1
                For A As Integer = 0 To 5
                    If aryLocalAddr(I).ToString = IPAddm(A) Then
                        IPAddnum = IPAddm(A)
                        Bfalge = True
                        GoTo netok
                    End If
                Next
            Next

netok:
            If IPAddnum = "192.168.2.100" Then
                newsetM(0) = True
            ElseIf IPAddnum = "192.168.2.101" Then
                newsetM(1) = True
            ElseIf IPAddnum = "192.168.2.102" Then
                newsetM(2) = True
            ElseIf IPAddnum = "192.168.2.103" Then
                newsetM(3) = True
            ElseIf IPAddnum = "192.168.2.104" Then
                newsetM(4) = True
            ElseIf IPAddnum = "192.168.2.105" Then
                newsetM(5) = True
            End If
            If Bfalge = False Then
                AppendInfoToTextBox(vbCrLf + "多台联机网口IP设置错误，请重新设置!")
                GoTo D
            End If
            StartListen22(mmServer(0), IPAddnum, "9000")
D:
        Catch ex As Exception
            MsgBox(ex.Message.ToString)
        End Try
    End Sub

    Public Sub StartListen22(ByVal server As Socket, ByVal ServerIP As String, ByVal portnum As Integer)

        Try
            server = New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp) '使用指定的地址族、套接字类型和协议初始化 Socket 类的新实例。
            server.Bind(New IPEndPoint(Net.IPAddress.Parse(ServerIP), portnum)) ' ‘ '  ip地址统一
            server.Listen(10)
            server.BeginAccept(AddressOf OnAccepted22, server)
        Catch ex As Exception
            MsgBox("StartListen:" & ex.Message.ToString)
        End Try

    End Sub

    Dim m_aryClients1 As New ArrayList

    Protected Overridable Sub OnAccepted22(ByVal ar As IAsyncResult)

        Try

            Dim listener As Socket = CType(ar.AsyncState, Socket)
            Dim handler As Socket = listener.EndAccept(ar)
            m_aryClients1.Add(handler)

            AppendInfoToTextBox(vbCrLf + "客户端:" + handler.LocalEndPoint.ToString() + "已连接")

            Dim state As New StateObject
            state.workSocket = handler

            listener.BeginAccept(AddressOf OnAccepted22, listener)

            handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, New AsyncCallback(AddressOf ReadCallback1), state)
        Catch ex As Exception
            MsgBox("OnAccepted22:" & ex.Message.ToString)
        End Try

    End Sub

    Protected Overridable Sub ReadCallback1(ByVal ar As IAsyncResult)
        Try
            Dim content As String = String.Empty
            Dim state As StateObject = CType(ar.AsyncState, StateObject)
            Dim handler As Socket = state.workSocket
            Dim bytesRead As Integer = handler.EndReceive(ar)
            If bytesRead = 0 Then
                AppendInfoToTextBox(vbCrLf + "客户端:" + handler.LocalEndPoint.ToString() + "已断开")
                'm_aryClients.Remove(handler)
                handler.Close()
                Return
            End If
            RunningCCD = True
            RecevDataProcess2(handler, Encoding.ASCII.GetString(state.buffer))
            Array.Clear(state.buffer, 0, bytesRead)
            handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, New AsyncCallback(AddressOf ReadCallback1), state)
        Catch ex As System.Exception
            AppendInfoToTextBox("ReadCallback1:" & ex.Message.ToString)
        End Try
    End Sub

    ''' <summary>
    ''' 锁附信息发送至从机
    ''' </summary>
    ''' <param name="station"></param>
    ''' <param name="cChanpin"></param>
    ''' <param name="cSN"></param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Private Function SendSN(ByVal cSN As String) As Boolean

        Dim re As Boolean = False
        'Dim result As String = ""
        Dim SendDate As String = ""
        Dim station As String = ""
        Try

            'result = isOK
            'SendDate = station.ToString & "," & cChanpin & "," & cSN & "," & result    '测试
            'Globalfunc.SendDataNORePly(SendDate, "192.168.1.101", "10000", "UTF8")    '测试

            ' newset(2)主机   newset(3)从机1  newset(4)从机2  newset(5)从机3
            SendDate = cSN & ";" & Chanpin & ";,!"
            If newsetM(0) = True Then

                'SendDate = cSN & "," & result & ","
                SendData(SendDate, IPAddm(1), "9000")
            End If
            If newsetM(1) = True Then

                'SendDate = cSN & "," & result & ","
                SendData(SendDate, IPAddm(2), "9000")
            End If
            If newsetM(2) = True Then

                ' SendDate = cSN & "," & result & ","
                SendData(SendDate, IPAddm(3), "9000")
            End If
            If newsetM(3) = True Then

                ' SendDate = cSN & "," & result & ","
                SendData(SendDate, IPAddm(4), "9000")
            End If
            If newsetM(4) = True Then

                ' SendDate = cSN & "," & result & ","
                SendData(SendDate, IPAddm(5), "9000")
            End If
            If newsetM(5) = True Then

                ' SendDate = cSN & "," & result & ","
                SendData(SendDate, IPAddm(6), "9000")
            End If
            'SN_TextBox.Text = ""
            AppendInfoToTextBox("向后一台发送SN数据:" & SendDate & vbCrLf)
            re = True
            Return re
        Catch ex As Exception
            AppendInfoToTextBox("多台联机发送异常：" & ex.Message.ToString)
            re = False
            Return re
        End Try
    End Function

#End Region

    Private Sub RecevDataProcess2(ByRef MySocket2 As Socket, ByVal StrReceData2 As String)
        AppendInfoToTextBox("接收前一台数据:" + StrReceData2 + vbCrLf)
        Dim recdata() As String = StrReceData2.Split(",")
        Dim curProd As New ProdInfo
        If recdata(0) = "Y" Then
            'TextBox_SN.Text = recdata(1).ToString()
            curProd.sn = recdata(1).ToString()
            curProd.model_name = recdata(2).ToString()
            'End If
            If curProd.sn <> "" Then
                SN_Queue.Enqueue(curProd)
                showSNQueueFlag = True
            End If
        End If
    End Sub

#End Region

    Public Sub InitTcpSever() '初始化TCP服务器

        Dim serport As Integer = 8000   '端口号
        'Dim IPAdd As String = "10.0.20.106"
        Dim IPAdd As String = "192.168.1.101"
        Dim aryLocalAddr As IPAddress()
        Dim strHostName As String
        Dim bFlag As Boolean = True
        Try
restart:
            strHostName = Dns.GetHostName()  '获取本地计算机的主机名
            Dim ipEntry As IPHostEntry = Dns.GetHostByName(strHostName)  '获取指定 DNS 主机名的 DNS 信息  IPHostEntry(为 Internet 主机地址信息提供容器类)
            'Public Shared Function GetHostByName(ByVal hostName As String) As System.Net.IPHostEntry
            aryLocalAddr = ipEntry.AddressList  '获取与主机关联的 IP 地址列表

            If aryLocalAddr Is Nothing Then
                System.Threading.Thread.Sleep(1000)
                GoTo restart
            End If
            If aryLocalAddr.Length < 1 Then
                System.Threading.Thread.Sleep(1000)
                GoTo restart
            End If
            For K As Integer = 0 To aryLocalAddr.Length - 1
                If aryLocalAddr(K).ToString <> IPAdd Then
                    machineInfo.IP = aryLocalAddr(K).ToString
                    machineInfoStatus.IP = machineInfo.IP
                End If
            Next
            For I As Integer = 0 To aryLocalAddr.Length - 1
                If aryLocalAddr(I).ToString = IPAdd Then
                    GoTo netok
                End If
            Next
            System.Threading.Thread.Sleep(1000)

            'If IPAdd = "192.168.1.101" Then
            '    IPAdd = "10.0.20.46"
            'Else
            '    IPAdd = "192.168.1.101"
            'End If
            'AppendInfoToTextBox("视觉软件IP：" & IPAdd)
            GoTo restart
netok:

            mServer = New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp) '使用指定的地址族、套接字类型和协议初始化 Socket 类的新实例。
            'mServer.Bind(New IPEndPoint(aryLocalAddr(0), serport))
            Try
                mServer.Bind(New IPEndPoint(Net.IPAddress.Parse(IPAdd), serport)) ' ‘ '  ip地址统一
            Catch ex As Exception
                'While (bFlag)

                'End While
            End Try
            mServer.Listen(10)
            mServer.BeginAccept(AddressOf OnAccepted, mServer)

            mServer1 = New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp) '使用指定的地址族、套接字类型和协议初始化 Socket 类的新实例。
            'mServer.Bind(New IPEndPoint(aryLocalAddr(0), serport))
            Try
                mServer1.Bind(New IPEndPoint(Net.IPAddress.Parse(IPAdd), serport + 1)) ' ‘ '  ip地址统一
            Catch ex As Exception
                'While (bFlag)

                'End While
            End Try
            mServer1.Listen(10)
            mServer1.BeginAccept(AddressOf OnAccepted1, mServer1)

            mServer2 = New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp) '使用指定的地址族、套接字类型和协议初始化 Socket 类的新实例。
            'mServer.Bind(New IPEndPoint(aryLocalAddr(0), serport))
            Try
                mServer2.Bind(New IPEndPoint(Net.IPAddress.Parse(IPAdd), serport + 2)) ' ‘ '  ip地址统一
            Catch ex As Exception
                'While (bFlag)

                'End While
            End Try
            mServer2.Listen(10)
            mServer2.BeginAccept(AddressOf OnAccepted2, mServer2)

            mServer3 = New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp) '使用指定的地址族、套接字类型和协议初始化 Socket 类的新实例。
            'mServer.Bind(New IPEndPoint(aryLocalAddr(0), serport))
            Try
                mServer3.Bind(New IPEndPoint(Net.IPAddress.Parse(IPAdd), serport + 3)) ' ‘ '  ip地址统一
            Catch ex As Exception
                'While (bFlag)

                'End While
            End Try
            mServer3.Listen(10)
            mServer3.BeginAccept(AddressOf OnAccepted3, mServer3)

            mServer4 = New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp) '使用指定的地址族、套接字类型和协议初始化 Socket 类的新实例。
            'mServer.Bind(New IPEndPoint(aryLocalAddr(0), serport))
            Try
                mServer4.Bind(New IPEndPoint(Net.IPAddress.Parse(IPAdd), serport + 4)) ' ‘ '  ip地址统一
            Catch ex As Exception
                'While (bFlag)

                'End While
            End Try
            mServer4.Listen(10)
            mServer4.BeginAccept(AddressOf OnAccepted4, mServer4)

            mServer5 = New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp) '使用指定的地址族、套接字类型和协议初始化 Socket 类的新实例。
            'mServer.Bind(New IPEndPoint(aryLocalAddr(0), serport))
            Try
                mServer5.Bind(New IPEndPoint(Net.IPAddress.Parse(IPAdd), serport + 5)) ' ‘ '  ip地址统一
            Catch ex As Exception
                'While (bFlag)

                'End While
            End Try
            mServer5.Listen(10)
            mServer5.BeginAccept(AddressOf OnAccepted5, mServer5)

            '8006
            mServer6 = New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp) '使用指定的地址族、套接字类型和协议初始化 Socket 类的新实例。
            'mServer.Bind(New IPEndPoint(aryLocalAddr(0), serport))
            Try
                mServer6.Bind(New IPEndPoint(Net.IPAddress.Parse(IPAdd), serport + 6)) ' ‘ '  ip地址统一
            Catch ex As Exception
                'While (bFlag)

                'End While
            End Try
            mServer6.Listen(10)
            mServer6.BeginAccept(AddressOf OnAccepted6, mServer6)

            '8007
            mServer7 = New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp) '使用指定的地址族、套接字类型和协议初始化 Socket 类的新实例。
            'mServer.Bind(New IPEndPoint(aryLocalAddr(0), serport))
            Try
                mServer7.Bind(New IPEndPoint(Net.IPAddress.Parse(IPAdd), serport + 7)) ' ‘ '  ip地址统一
            Catch ex As Exception
                'While (bFlag)

                'End While
            End Try
            mServer7.Listen(10)
            mServer7.BeginAccept(AddressOf OnAccepted7, mServer7)

            '8008
            mServer8 = New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp) '使用指定的地址族、套接字类型和协议初始化 Socket 类的新实例。
            'mServer.Bind(New IPEndPoint(aryLocalAddr(0), serport))
            Try
                mServer8.Bind(New IPEndPoint(Net.IPAddress.Parse(IPAdd), serport + 8)) ' ‘ '  ip地址统一
            Catch ex As Exception
                'While (bFlag)

                'End While
            End Try
            mServer8.Listen(10)
            mServer8.BeginAccept(AddressOf OnAccepted8, mServer8)

            '8009
            mServer9 = New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp) '使用指定的地址族、套接字类型和协议初始化 Socket 类的新实例。
            'mServer.Bind(New IPEndPoint(aryLocalAddr(0), serport))
            Try
                mServer9.Bind(New IPEndPoint(Net.IPAddress.Parse(IPAdd), serport + 9)) ' ‘ '  ip地址统一
            Catch ex As Exception
                'While (bFlag)

                'End While
            End Try
            mServer9.Listen(10)
            mServer9.BeginAccept(AddressOf OnAccepted9, mServer9)

            '8010
            mServer10 = New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp) '使用指定的地址族、套接字类型和协议初始化 Socket 类的新实例。
            'mServer.Bind(New IPEndPoint(aryLocalAddr(0), serport))
            Try
                mServer10.Bind(New IPEndPoint(Net.IPAddress.Parse(IPAdd), serport + 10)) ' ‘ '  ip地址统一
            Catch ex As Exception
                'While (bFlag)

                'End While
            End Try
            mServer10.Listen(10)
            mServer10.BeginAccept(AddressOf OnAccepted10, mServer10)

            '8011
            mServer11 = New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp) '使用指定的地址族、套接字类型和协议初始化 Socket 类的新实例。
            'mServer.Bind(New IPEndPoint(aryLocalAddr(0), serport))
            Try
                mServer11.Bind(New IPEndPoint(Net.IPAddress.Parse(IPAdd), serport + 11)) ' ‘ '  ip地址统一
            Catch ex As Exception
                'While (bFlag)

                'End While
            End Try
            mServer11.Listen(10)
            mServer11.BeginAccept(AddressOf OnAccepted11, mServer11)

            '8012
            mServer12 = New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp) '使用指定的地址族、套接字类型和协议初始化 Socket 类的新实例。
            'mServer.Bind(New IPEndPoint(aryLocalAddr(0), serport))
            Try
                mServer12.Bind(New IPEndPoint(Net.IPAddress.Parse(IPAdd), serport + 12)) ' ‘ '  ip地址统一
            Catch ex As Exception
                'While (bFlag)

                'End While
            End Try
            mServer12.Listen(10)
            mServer12.BeginAccept(AddressOf OnAccepted12, mServer12)

            '8013
            mServer13 = New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp) '使用指定的地址族、套接字类型和协议初始化 Socket 类的新实例。
            'mServer.Bind(New IPEndPoint(aryLocalAddr(0), serport))
            Try
                mServer13.Bind(New IPEndPoint(Net.IPAddress.Parse(IPAdd), serport + 13)) ' ‘ '  ip地址统一
            Catch ex As Exception
                'While (bFlag)

                'End While
            End Try
            mServer13.Listen(10)
            mServer13.BeginAccept(AddressOf OnAccepted13, mServer13)
            '8014
            mServer14 = New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp) '使用指定的地址族、套接字类型和协议初始化 Socket 类的新实例。
            'mServer.Bind(New IPEndPoint(aryLocalAddr(0), serport))
            Try
                mServer14.Bind(New IPEndPoint(Net.IPAddress.Parse(IPAdd), serport + 14)) ' ‘ '  ip地址统一
            Catch ex As Exception
                'While (bFlag)

                'End While
            End Try
            mServer14.Listen(10)
            mServer14.BeginAccept(AddressOf OnAccepted14, mServer14)
            'Public Function BeginAccept(ByVal callback As System.AsyncCallback, ByVal state As Object) As System.IAsyncResult
        Catch ex As System.Exception
            WriteInspecLog(TSLog, "InitTcpSever()Err" & vbTab & ex.StackTrace)
        End Try

    End Sub

    Protected Overridable Sub OnAccepted(ByVal ar As IAsyncResult)

        Try
            Dim listener As Socket = CType(ar.AsyncState, Socket)
            ' End the operation.
            Dim handler As Socket = listener.EndAccept(ar)
            m_aryClients.Add(handler)
            'AddClientToListBox(handler.RemoteEndPoint.ToString()) 'RemoteEndPoint(获取远程终结点)
            'TextRecv.Text = handler.RemoteEndPoint.ToString()
            AppendInfoToTextBox(vbCrLf + "客户端:" + handler.LocalEndPoint.ToString() + "已连接")
            'AddInfoToTextBox("客户端:" + handler.RemoteEndPoint.ToString() + "已连接")
            Dim state As New StateObject
            state.workSocket = handler
            mServer.BeginAccept(AddressOf OnAccepted, mServer)
            handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, New AsyncCallback(AddressOf ReadCallback), state)
        Catch ex As Exception

        End Try

    End Sub

    Protected Overridable Sub OnAccepted1(ByVal ar As IAsyncResult)

        Try
            Dim listener As Socket = CType(ar.AsyncState, Socket)
            ' End the operation.
            Dim handler As Socket = listener.EndAccept(ar)
            m_aryClients.Add(handler)

            'AddClientToListBox(handler.RemoteEndPoint.ToString()) 'RemoteEndPoint(获取远程终结点)
            'TextRecv.Text = handler.RemoteEndPoint.ToString()
            AppendInfoToTextBox(vbCrLf + "客户端:" + handler.LocalEndPoint.ToString() + "已连接")
            'AddInfoToTextBox("客户端:" + handler.RemoteEndPoint.ToString() + "已连接")
            Dim state As New StateObject
            state.workSocket = handler
            mServer1.BeginAccept(AddressOf OnAccepted1, mServer1)
            handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, New AsyncCallback(AddressOf ReadCallback), state)
        Catch ex As Exception

        End Try

    End Sub

    Protected Overridable Sub OnAccepted2(ByVal ar As IAsyncResult)

        Try
            Dim listener As Socket = CType(ar.AsyncState, Socket)
            ' End the operation.
            Dim handler As Socket = listener.EndAccept(ar)
            m_aryClients.Add(handler)

            'AddClientToListBox(handler.RemoteEndPoint.ToString()) 'RemoteEndPoint(获取远程终结点)
            'TextRecv.Text = handler.RemoteEndPoint.ToString()
            AppendInfoToTextBox(vbCrLf + "客户端:" + handler.LocalEndPoint.ToString() + "已连接")
            'AddInfoToTextBox("客户端:" + handler.RemoteEndPoint.ToString() + "已连接")
            Dim state As New StateObject
            state.workSocket = handler
            mServer2.BeginAccept(AddressOf OnAccepted2, mServer2)
            handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, New AsyncCallback(AddressOf ReadCallback), state)
        Catch ex As Exception

        End Try

    End Sub

    Protected Overridable Sub OnAccepted3(ByVal ar As IAsyncResult)

        Try
            Dim listener As Socket = CType(ar.AsyncState, Socket)
            ' End the operation.
            Dim handler As Socket = listener.EndAccept(ar)
            m_aryClients.Add(handler)

            'AddClientToListBox(handler.RemoteEndPoint.ToString()) 'RemoteEndPoint(获取远程终结点)
            'TextRecv.Text = handler.RemoteEndPoint.ToString()
            AppendInfoToTextBox(vbCrLf + "客户端:" + handler.LocalEndPoint.ToString() + "已连接")
            'AddInfoToTextBox("客户端:" + handler.RemoteEndPoint.ToString() + "已连接")
            Dim state As New StateObject
            state.workSocket = handler
            mServer3.BeginAccept(AddressOf OnAccepted3, mServer3)
            handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, New AsyncCallback(AddressOf ReadCallback), state)
        Catch ex As Exception

        End Try

    End Sub

    Protected Overridable Sub OnAccepted4(ByVal ar As IAsyncResult)

        Try
            Dim listener As Socket = CType(ar.AsyncState, Socket)
            ' End the operation.
            Dim handler As Socket = listener.EndAccept(ar)
            m_aryClients.Add(handler)

            'AddClientToListBox(handler.RemoteEndPoint.ToString()) 'RemoteEndPoint(获取远程终结点)
            'TextRecv.Text = handler.RemoteEndPoint.ToString()
            AppendInfoToTextBox(vbCrLf + "客户端:" + handler.LocalEndPoint.ToString() + "已连接")
            'AddInfoToTextBox("客户端:" + handler.RemoteEndPoint.ToString() + "已连接")
            Dim state As New StateObject
            state.workSocket = handler
            mServer4.BeginAccept(AddressOf OnAccepted4, mServer4)
            handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, New AsyncCallback(AddressOf ReadCallback), state)
        Catch ex As Exception

        End Try

    End Sub

    Protected Overridable Sub OnAccepted5(ByVal ar As IAsyncResult)

        Try

            Dim listener As Socket = CType(ar.AsyncState, Socket)
            ' End the operation.
            Dim handler As Socket = listener.EndAccept(ar)
            m_aryClients.Add(handler)

            'AddClientToListBox(handler.RemoteEndPoint.ToString()) 'RemoteEndPoint(获取远程终结点)
            'TextRecv.Text = handler.RemoteEndPoint.ToString()
            AppendInfoToTextBox(vbCrLf + "客户端:" + handler.LocalEndPoint.ToString() + "已连接")
            'AddInfoToTextBox("客户端:" + handler.RemoteEndPoint.ToString() + "已连接")
            Dim state As New StateObject
            state.workSocket = handler
            mServer5.BeginAccept(AddressOf OnAccepted5, mServer5)
            handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, New AsyncCallback(AddressOf ReadCallback), state)
        Catch ex As Exception

        End Try

    End Sub

    Protected Overridable Sub OnAccepted6(ByVal ar As IAsyncResult)

        Try

            Dim listener As Socket = CType(ar.AsyncState, Socket)
            ' End the operation.
            Dim handler As Socket = listener.EndAccept(ar)
            m_aryClients.Add(handler)

            'AddClientToListBox(handler.RemoteEndPoint.ToString()) 'RemoteEndPoint(获取远程终结点)
            'TextRecv.Text = handler.RemoteEndPoint.ToString()
            AppendInfoToTextBox(vbCrLf + "客户端:" + handler.LocalEndPoint.ToString() + "已连接")
            'AddInfoToTextBox("客户端:" + handler.RemoteEndPoint.ToString() + "已连接")
            Dim state As New StateObject
            state.workSocket = handler
            mServer6.BeginAccept(AddressOf OnAccepted6, mServer6)
            handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, New AsyncCallback(AddressOf ReadCallback), state)
        Catch ex As Exception

        End Try

    End Sub

    Protected Overridable Sub OnAccepted7(ByVal ar As IAsyncResult)

        Try

            Dim listener As Socket = CType(ar.AsyncState, Socket)
            ' End the operation.
            Dim handler As Socket = listener.EndAccept(ar)
            m_aryClients.Add(handler)

            'AddClientToListBox(handler.RemoteEndPoint.ToString()) 'RemoteEndPoint(获取远程终结点)
            'TextRecv.Text = handler.RemoteEndPoint.ToString()
            AppendInfoToTextBox(vbCrLf + "客户端:" + handler.LocalEndPoint.ToString() + "已连接")
            'AddInfoToTextBox("客户端:" + handler.RemoteEndPoint.ToString() + "已连接")
            Dim state As New StateObject
            state.workSocket = handler
            mServer7.BeginAccept(AddressOf OnAccepted7, mServer7)
            handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, New AsyncCallback(AddressOf ReadCallback), state)
        Catch ex As Exception

        End Try

    End Sub

    Protected Overridable Sub OnAccepted8(ByVal ar As IAsyncResult)

        Try

            Dim listener As Socket = CType(ar.AsyncState, Socket)
            ' End the operation.
            Dim handler As Socket = listener.EndAccept(ar)
            m_aryClients.Add(handler)

            'AddClientToListBox(handler.RemoteEndPoint.ToString()) 'RemoteEndPoint(获取远程终结点)
            'TextRecv.Text = handler.RemoteEndPoint.ToString()
            AppendInfoToTextBox(vbCrLf + "客户端:" + handler.LocalEndPoint.ToString() + "已连接")
            'AddInfoToTextBox("客户端:" + handler.RemoteEndPoint.ToString() + "已连接")
            Dim state As New StateObject
            state.workSocket = handler
            mServer8.BeginAccept(AddressOf OnAccepted8, mServer8)
            handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, New AsyncCallback(AddressOf ReadCallback), state)
        Catch ex As Exception

        End Try

    End Sub

    Protected Overridable Sub OnAccepted9(ByVal ar As IAsyncResult)

        Try

            Dim listener As Socket = CType(ar.AsyncState, Socket)
            ' End the operation.
            Dim handler As Socket = listener.EndAccept(ar)
            m_aryClients.Add(handler)

            'AddClientToListBox(handler.RemoteEndPoint.ToString()) 'RemoteEndPoint(获取远程终结点)
            'TextRecv.Text = handler.RemoteEndPoint.ToString()
            AppendInfoToTextBox(vbCrLf + "客户端:" + handler.LocalEndPoint.ToString() + "已连接")
            'AddInfoToTextBox("客户端:" + handler.RemoteEndPoint.ToString() + "已连接")
            Dim state As New StateObject
            state.workSocket = handler
            mServer9.BeginAccept(AddressOf OnAccepted9, mServer9)
            handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, New AsyncCallback(AddressOf ReadCallback), state)
        Catch ex As Exception

        End Try

    End Sub

    Protected Overridable Sub OnAccepted10(ByVal ar As IAsyncResult)

        Try

            Dim listener As Socket = CType(ar.AsyncState, Socket)
            ' End the operation.
            Dim handler As Socket = listener.EndAccept(ar)
            m_aryClients.Add(handler)

            'AddClientToListBox(handler.RemoteEndPoint.ToString()) 'RemoteEndPoint(获取远程终结点)
            'TextRecv.Text = handler.RemoteEndPoint.ToString()
            AppendInfoToTextBox(vbCrLf + "客户端:" + handler.LocalEndPoint.ToString() + "已连接")
            'AddInfoToTextBox("客户端:" + handler.RemoteEndPoint.ToString() + "已连接")
            Dim state As New StateObject
            state.workSocket = handler
            mServer10.BeginAccept(AddressOf OnAccepted10, mServer10)
            handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, New AsyncCallback(AddressOf ReadCallback), state)
        Catch ex As Exception

        End Try

    End Sub

    Protected Overridable Sub OnAccepted11(ByVal ar As IAsyncResult)

        Try

            Dim listener As Socket = CType(ar.AsyncState, Socket)
            ' End the operation.
            Dim handler As Socket = listener.EndAccept(ar)
            m_aryClients.Add(handler)

            'AddClientToListBox(handler.RemoteEndPoint.ToString()) 'RemoteEndPoint(获取远程终结点)
            'TextRecv.Text = handler.RemoteEndPoint.ToString()
            AppendInfoToTextBox(vbCrLf + "客户端:" + handler.LocalEndPoint.ToString() + "已连接")
            'AddInfoToTextBox("客户端:" + handler.RemoteEndPoint.ToString() + "已连接")
            Dim state As New StateObject
            state.workSocket = handler
            mServer11.BeginAccept(AddressOf OnAccepted11, mServer11)
            handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, New AsyncCallback(AddressOf ReadCallback), state)
        Catch ex As Exception

        End Try

    End Sub

    Protected Overridable Sub OnAccepted12(ByVal ar As IAsyncResult)

        Try

            Dim listener As Socket = CType(ar.AsyncState, Socket)
            ' End the operation.
            Dim handler As Socket = listener.EndAccept(ar)
            m_aryClients.Add(handler)

            'AddClientToListBox(handler.RemoteEndPoint.ToString()) 'RemoteEndPoint(获取远程终结点)
            'TextRecv.Text = handler.RemoteEndPoint.ToString()
            AppendInfoToTextBox(vbCrLf + "客户端:" + handler.LocalEndPoint.ToString() + "已连接")
            'AddInfoToTextBox("客户端:" + handler.RemoteEndPoint.ToString() + "已连接")
            Dim state As New StateObject
            state.workSocket = handler
            mServer12.BeginAccept(AddressOf OnAccepted12, mServer12)
            handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, New AsyncCallback(AddressOf ReadCallback), state)
        Catch ex As Exception

        End Try

    End Sub

    Protected Overridable Sub OnAccepted13(ByVal ar As IAsyncResult)

        Try

            Dim listener As Socket = CType(ar.AsyncState, Socket)
            ' End the operation.
            Dim handler As Socket = listener.EndAccept(ar)
            m_aryClients.Add(handler)

            'AddClientToListBox(handler.RemoteEndPoint.ToString()) 'RemoteEndPoint(获取远程终结点)
            'TextRecv.Text = handler.RemoteEndPoint.ToString()
            AppendInfoToTextBox(vbCrLf + "客户端:" + handler.LocalEndPoint.ToString() + "已连接")
            'AddInfoToTextBox("客户端:" + handler.RemoteEndPoint.ToString() + "已连接")
            Dim state As New StateObject
            state.workSocket = handler
            mServer13.BeginAccept(AddressOf OnAccepted13, mServer13)
            handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, New AsyncCallback(AddressOf ReadCallback), state)
        Catch ex As Exception

        End Try

    End Sub

    Protected Overridable Sub OnAccepted14(ByVal ar As IAsyncResult)

        Try

            Dim listener As Socket = CType(ar.AsyncState, Socket)
            ' End the operation.
            Dim handler As Socket = listener.EndAccept(ar)
            m_aryClients.Add(handler)

            'AddClientToListBox(handler.RemoteEndPoint.ToString()) 'RemoteEndPoint(获取远程终结点)
            'TextRecv.Text = handler.RemoteEndPoint.ToString()
            AppendInfoToTextBox(vbCrLf + "客户端:" + handler.LocalEndPoint.ToString() + "已连接")
            'AddInfoToTextBox("客户端:" + handler.RemoteEndPoint.ToString() + "已连接")
            Dim state As New StateObject
            state.workSocket = handler
            mServer14.BeginAccept(AddressOf OnAccepted14, mServer14)
            handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, New AsyncCallback(AddressOf ReadCallback), state)
        Catch ex As Exception

        End Try

    End Sub

    Public Sub AppendInfoToTextBox(ByVal s As String)
        If (TxtResult1.InvokeRequired) Then
            Dim cb As AddRecvToText = New AddRecvToText(AddressOf AppendInfoToTextBox)
            Invoke(cb, s)
        Else
            TxtResult1.AppendText(s + vbCrLf)

            Method.WritePathTxt(DebugPath & "\log\", "System_Result_" & Format(Date.Now.Date, "yyyyMMdd") & ".txt", Format(DateAndTime.Now, "yyyy-MM-dd HH:mm:ss") & vbCrLf & s)

            'TxtResult1.AppendText(s + vbCrLf)
            'Dim openresult As Boolean = Exists(DebugPath & "\log" & "\" & "System_Result_" & Format(Date.Now.Date, "yyyyMMdd") & ".txt")
            'Dim fileNum As Integer
            'fileNum = FreeFile()
            'If openresult = False Then
            '    FileOpen(fileNum, DebugPath & "\log" & "\" & "System_Result_" & Format(Date.Now.Date, "yyyyMMdd") & ".txt", OpenMode.Append)
            '    FileClose(fileNum)
            'End If
            ''文件名
            'Dim strSaveFilename As String
            'strSaveFilename = DebugPath & "\log" & "\" & "System_Result_" & Format(Date.Now.Date, "yyyyMMdd") & ".txt"

            ''打开文件
            'FileOpen(fileNum, strSaveFilename, OpenMode.Append)

            ''存储文件title
            'Print(fileNum, "System_Result_" & Date.Now & vbTab)

            ''存储到文件中
            'Print(fileNum, s & vbCrLf)
            ''关闭文件
            'FileClose(fileNum)
        End If
    End Sub

    Public Sub AppendMESToTextBox(ByVal s As String)
        If (TxtResult1.InvokeRequired) Then
            Dim cb As AddRecvToText = New AddRecvToText(AddressOf AppendMESToTextBox)
            Invoke(cb, s)
        Else
            TxtResult1.AppendText(s + vbCrLf)

            Method.WritePathTxt(DebugPath & "\MesLog\", "System_Result_" & Format(Date.Now.Date, "yyyyMMdd") & ".txt", Format(DateAndTime.Now, "yyyy-MM-dd HH:mm:ss") & vbCrLf & s)

            'TxtResult1.AppendText(s + vbCrLf)
            'Dim openresult As Boolean = Exists(DebugPath & "\log" & "\" & "System_Result_" & Format(Date.Now.Date, "yyyyMMdd") & ".txt")
            'Dim fileNum As Integer
            'fileNum = FreeFile()
            'If openresult = False Then
            '    FileOpen(fileNum, DebugPath & "\log" & "\" & "System_Result_" & Format(Date.Now.Date, "yyyyMMdd") & ".txt", OpenMode.Append)
            '    FileClose(fileNum)
            'End If
            ''文件名
            'Dim strSaveFilename As String
            'strSaveFilename = DebugPath & "\log" & "\" & "System_Result_" & Format(Date.Now.Date, "yyyyMMdd") & ".txt"

            ''打开文件
            'FileOpen(fileNum, strSaveFilename, OpenMode.Append)

            ''存储文件title
            'Print(fileNum, "System_Result_" & Date.Now & vbTab)

            ''存储到文件中
            'Print(fileNum, s & vbCrLf)
            ''关闭文件
            'FileClose(fileNum)
        End If
    End Sub

    Protected Sub AddInfoToTextBox(ByVal s As String)
        If (TxtResult1.InvokeRequired) Then
            Dim cb As AddClientToList = New AddClientToList(AddressOf AddInfoToTextBox)
            'Public Function Invoke(ByVal method As System.Delegate, ByVal ParamArray args() As Object) As Object
            Invoke(cb, s)
        Else
            TxtResult1.Text = s + vbCrLf
        End If
    End Sub

    Protected Sub AddErrMsgToTextBox(ByVal s As String)
        If (TextBox_ErrMsg.InvokeRequired) Then
            Dim cb As AddClientToList = New AddClientToList(AddressOf AddErrMsgToTextBox)
            'Public Function Invoke(ByVal method As System.Delegate, ByVal ParamArray args() As Object) As Object
            Invoke(cb, s)
        Else
            TextBox_ErrMsg.Clear()
            TextBox_ErrMsg.AppendText(s + vbCrLf + DateTime.Now + vbCrLf)
            Method.WritePathTxt(DebugPath & "\Err_log\", "System_ERR_" & Format(Date.Now.Date, "yyyyMMdd") & ".txt", Format(DateAndTime.Now, "yyyy-MM-dd HH:mm:ss") & vbCrLf & s)

            'TextBox_ErrMsg.Clear()
            'TextBox_ErrMsg.AppendText(s + vbCrLf + DateTime.Now + vbCrLf)
            'Dim openresult As Boolean = Exists(DebugPath & "\Err_log" & "\" & "System_ERR_" & Format(Date.Now.Date, "yyyyMMdd") & ".txt")
            'Dim fileNum As Integer
            'fileNum = FreeFile()
            'If openresult = False Then
            '    FileOpen(fileNum, DebugPath & "\Err_log" & "\" & "System_ERR_" & Format(Date.Now.Date, "yyyyMMdd") & ".txt", OpenMode.Append)
            '    FileClose(fileNum)
            'End If
            ''文件名
            'Dim strSaveFilename As String
            'strSaveFilename = DebugPath & "\Err_log" & "\" & "System_ERR_" & Format(Date.Now.Date, "yyyyMMdd") & ".txt"

            ''打开文件
            'FileOpen(fileNum, strSaveFilename, OpenMode.Append)

            ''存储文件title
            'Print(fileNum, "System_Result_" & Date.Now & vbTab)

            ''存储到文件中
            'Print(fileNum, s & vbCrLf)
            ''关闭文件
            'FileClose(fileNum)
        End If
    End Sub

    Protected Overridable Sub ReadCallback(ByVal ar As IAsyncResult)
        Try
            Dim content As String = String.Empty
            Dim state As StateObject = CType(ar.AsyncState, StateObject)
            Dim handler As Socket = state.workSocket
            Dim bytesRead As Integer = handler.EndReceive(ar)
            If bytesRead = 0 Then
                'DeleteClientFromListBox(handler.RemoteEndPoint.ToString())
                AppendInfoToTextBox(vbCrLf + "客户端:" + handler.LocalEndPoint.ToString() + "已断开")
                m_aryClients.Remove(handler)
                handler.Close()

                Return
            End If
            'AppendInfoToTextBox(Encoding.ASCII.GetString(state.buffer))
            'Dim mis As Integer = Date.Now.Millisecond
            'AddInfoToInfoTextBox(mis)
            RunningCCD = True
            '  FirstCameraImageProcess(handler, "m")
            RecevDataProcess(handler, Encoding.ASCII.GetString(state.buffer))
            Array.Clear(state.buffer, 0, bytesRead)
            handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, New AsyncCallback(AddressOf ReadCallback), state)
            'Dim stss As String = "1456"
        Catch ex As System.Exception
            'MsgBox(ex.StackTrace.ToString & vbCrLf & ex.Message.ToString)
            AddErrMsgToTextBox(ex.StackTrace.ToString & vbCrLf & ex.Message.ToString)
        End Try
    End Sub 'ReadCallback

    Dim MesScrewWorkData As New SCADA_ScrewWorkData.Write
    Dim MesScrewCT, MesScrewNL As String

    Private Sub RecevDataProcess(ByRef MySocket As Socket, ByVal StrReceData As String)

        endTime_SD = DateTime.Now
        If startTime_SD <> DateTime.MinValue Then
            shutDownTime = Format((endTime_SD.Ticks - startTime_SD.Ticks) / 10000000, "0.0")
            Todaycount.ShutDownTime += shutDownTime
            'Todaycount.ShutDownTime = Format(Todaycount.ShutDownTime, "0.0")
            SDTime.Text = Format(Todaycount.ShutDownTime, "0.0")
            startTime_SD = DateTime.MinValue
        End If
        ' Dim barrSend As Byte() = Encoding.ASCII.GetBytes(StrReceData)
        Dim strAlarmInfo As String = ""
        Dim ClientSocketIndex As Integer = 0
        AppendInfoToTextBox("接收信息：" + StrReceData + vbCrLf)
        TextBox_RunStatus.Text = "Run"
        TextBox_RunStatus.BackColor = Color.Lime
        machineInfoStatus.Status = "0"
        machineInfoStatus.ErrorCode = ""
        ErrorCode.Text = "NA"
        ErrorCode.BackColor = Color.WhiteSmoke
        'AddErrMsgToTextBox("")
        '已用数字: "1"; "7"; "2";
        '已用字母:"w+5/6"; "E";"SC"; "C & CY"; "P"; "N"; "R"; "A+S/C"; "s,1/2/3/4,螺丝颗号"; "M,Run/IDLE/Shutdown,ErrCode"
        'SendData
        Dim MesData() As String = StrReceData.Split(",")

        If MesData(0) = "MESDATA" Then
            Dim byteSend As Byte()
            '记录单颗螺丝坐标，扭力等数据
            If MesData(1) = "POINT" Then
                Try
                    Dim MesPoint As New SCADA_ScrewWorkData.PointParameter
                    MesPoint.X = MesData(2)
                    MesPoint.Y = MesData(3)
                    MesPoint.Z = MesData(4)
                    MesPoint.ScrewCT = MesScrewCT
                    MesPoint.ScrewLength = TextBox_CurScrewSN.Text
                    '以下都传空值
                    MesPoint.LockCircleQty = ""
                    MesPoint.FloatValue = ""
                    MesPoint.RacingSpeed = ""
                    If MesData(5) = "2" Then
                        MesPoint.NgItem = "螺丝"
                        MesPoint.Desc = "滑牙"
                        MesPoint.Torque = "0"
                    Else
                        MesPoint.NgItem = ""
                        MesPoint.Desc = ""
                        MesPoint.Torque = Torsion2
                    End If
                    MesPoint.TorqueUpper = ""
                    MesPoint.TorqueLower = ""
                    MesPoint.CircleQtyLower = ""
                    MesPoint.CircleQtyUpper = ""
                    MesPoint.FloatValueUpper = ""
                    MesPoint.FloatValueLower = ""
                    MesScrewWorkData.MAIN.PointParameter.Add(MesPoint)
                Catch ex As Exception
                    AddErrMsgToTextBox(ex.Message.ToString())
                End Try
                byteSend = Encoding.ASCII.GetBytes("OK" + vbCrLf)
                MySocket.Send(byteSend)
                AppendInfoToTextBox("回复'OK'" + vbCrLf)
                Return
            End If
            '记录产品锁附数据
            If MesData(1) = "SCREWNUM" Then
                Try
                    MesScrewWorkData.MAIN.LockScrewQty = MesData(2)
                    MesScrewWorkData.MAIN.NgScrewQty = MesData(3)
                    MesScrewWorkData.MAIN.ThrowScrewQty = MesData(4)
                    MesScrewWorkData.MAIN.PhotoTimes = MesData(5)
                    MesScrewWorkData.MAIN.Result = MesData(6)
                Catch ex As Exception
                    AddErrMsgToTextBox(ex.Message.ToString())
                End Try
                byteSend = Encoding.ASCII.GetBytes("OK" + vbCrLf)
                MySocket.Send(byteSend)
                AppendInfoToTextBox("回复'OK'" + vbCrLf)
                Return
            End If
            '发送报警信息
            If MesData(1) = "ERR" Then

                If newset(7) And MesConectFlag Then
                    Try
                        AppendMESToTextBox(Method.MES_SCADA_Warning(MesData(2), MesData(3), TextBox_OPID.Text))
                    Catch ex As Exception
                        AddErrMsgToTextBox(ex.Message.ToString())
                        MesConectFlag = False
                    End Try
                End If

                byteSend = Encoding.ASCII.GetBytes("OK" + vbCrLf)
                MySocket.Send(byteSend)

                AppendInfoToTextBox("回复'OK'" + vbCrLf)

                If MesData(2) = "Produce" Then
                    Try
                        Dim err As ErrClass = Method.FindInErrClassByerrCode(MesData(3))
                        AddErrMsgToTextBox(err.ErrMsg)
                    Catch ex As Exception
                        AddErrMsgToTextBox(ex.Message.ToString())
                    End Try
                Else
                    TextBox_ErrMsg.Clear()
                End If

                Return
            End If
            '发送设备状态
            If MesData(1) = "STATUS" Then

                If newset(7) And MesConectFlag Then
                    Try

                        AppendMESToTextBox(Method.MES_SCADA_StatusChange(MesData(2), TextBox_OPID.Text))
                    Catch ex As Exception
                        AddErrMsgToTextBox(ex.Message.ToString())
                        MesConectFlag = False
                    End Try
                End If

                TextBox_RunStatus.Text = MesData(2)
                If MesData(2).ToLower.Contains("run") Then
                    TextBox_RunStatus.BackColor = Color.Lime
                Else
                    TextBox_RunStatus.BackColor = Color.Red
                End If

                If MesData(2).ToLower.Contains("run") Then
                    TCmbPro.Enabled = False
                    'ToolStripButton17.Enabled = False
                ElseIf MesData(2).ToLower.Contains("stop") And (gPriority = 1 Or gPriority = 2) Then
                    TCmbPro.Enabled = True
                    'ToolStripButton17.Enabled = True
                End If

                byteSend = Encoding.ASCII.GetBytes("OK" + vbCrLf)
                MySocket.Send(byteSend)
                AppendInfoToTextBox("回复'OK'" + vbCrLf)
                Return
            End If

            Return
        End If

        If StrReceData(0) = "1" Then
            Dim NullDataByPCS As SFCSByPCS = New SFCSByPCS(30) '生产产品数据0
            DataByPCS = NullDataByPCS   'PCS信息清除
            ScrewOKCount = 0    'PCS记数清除
            IsScrewFail = True
            SNInfo.Status = "OK"
            'LoadAccess()
            StartTimeID = Format(DateAndTime.Now, "yyyy-MM-dd HH:mm:ss") '数据上传记录开始时间
            Dim strSendData As String = ""
            strSendData = CStr(Pget(6).YPosCompensate) + "," + CStr(Todaycount.PassCount) + "," + CStr(Retry_Times) + ","
            strSendData += CStr(Pget(0).XPosCompensate) + "," + CStr(Pget(0).YPosCompensate) + "," + CStr(Pget(0).ZPosCompensate) + ","
            strSendData += CStr(Pget(1).XPosCompensate) + "," + CStr(Pget(1).YPosCompensate) + "," + CStr(Pget(1).ZPosCompensate) + ","
            strSendData += CStr(Pget(4).XPosCompensate) + "," + CStr(Pget(4).YPosCompensate) + "," + CStr(Pget(4).ZPosCompensate) + ","
            strSendData += CStr(Pget(5).XPosCompensate) + "," + CStr(Pget(5).YPosCompensate) + "," + CStr(Pget(5).ZPosCompensate) + "," + vbCrLf
            Dim byteSend As Byte() = Encoding.ASCII.GetBytes(strSendData)   '拍照点偏移、$拍照点合格计数、$从新拍照次数
            MySocket.Send(byteSend)
            AppendInfoToTextBox("FirstCameraImageProcess(MySocket, StrReceData)")
            FirstCameraImageProcess(MySocket, StrReceData)
            MesScrewWorkData.MAIN.PointParameter.Clear()
            GoTo A
        End If

        If StrReceData(0) = "2" Then
            AppendInfoToTextBox("SecondCameraImageProcess(MySocket, StrReceData)")
            SecondCameraImageProcess(MySocket, StrReceData)
            MesScrewWorkData.MAIN.PointParameter.Clear()
            TextBox_ErrMsg.Clear()
            GoTo A
        End If

        '第3个拍照点
        If StrReceData(0) = "3" Then
            ThirdCameraImageProcess(MySocket, StrReceData)
            GoTo A
        End If

        'CCD拍照扫码点
        If StrReceData(0) = "4" Then
            CCD_cameraimagescancode(MySocket, StrReceData)
            GoTo A
        End If

        '判断扫描枪扫描判断是否切换产品
        If StrReceData(0) = "V" Then
            'Dim QH_JZ As String
            Dim ScanOK As Boolean = True
            Dim model As String
            model = Chanpin
            If SN_Queue.Count = 0 Then
                If newset(0) = False Then '没开启必须扫码
                    SN_Queue.Clear()
                    Dim p As New ProdInfo
                    p.model_name = Chanpin
                    p.sn = "Virtual_" & Format(DateTime.Now, "MMddHHmmss")
                    SN_Queue.Enqueue(p)
                    AppendInfoToTextBox("添加虚拟SN:" & p.sn)
                    showSNQueueFlag = True
                    ScanOK = False
                End If
            End If
            If SN_Queue.Count > 0 Then
                If SN_Queue(0).model_name <> "" And SN_Queue(0).model_name <> "NULL" Then
                    If Chanpin <> SN_Queue(0).model_name Then
                        AppendInfoToTextBox(Chanpin & "自动切换为:" & SN_Queue(0).model_name & "(" & SN_Queue(0).sn & ")")
                        initPro(SN_Queue(0).model_name)
                        InitSetting()
                        AppendInfoToTextBox(SN_Queue(0).model_name & "切换机型完成。")
                    End If
                End If
                ScanOK = True
            Else '队列中没有数据时
                AppendInfoToTextBox(vbCrLf & "扫码枪未扫入SN.")
            End If
            Dim byteSend As Byte() = Encoding.ASCII.GetBytes(Chanpin & "," & ScanOK & vbCrLf)
            MySocket.Send(byteSend)
            Can_Barcode = True '可以读码
            'If newset(0) = True Then
            '    model = 扫码模板管理.query(REPLY_MES)         '根据条形码数值进行查询代码
            '    AppendInfoToTextBox("条码确定产品名：" & model & vbCrLf)
            'End If

            'If model <> "" Then
            '    QH_JZ = model
            '    TCmbPro.Text = QH_JZ
            '    AppendInfoToTextBox("找到匹配模板：" & QH_JZ & vbCrLf)
            'Else
            '    QH_JZ = Chanpin
            '    AppendInfoToTextBox("未找到匹配模板,沿上一个模板：" & QH_JZ & vbCrLf)
            'End If
            'Dim byteSend As Byte() = Encoding.ASCII.GetBytes(QH_JZ & vbCrLf)
            'MySocket.Send(byteSend)
            'REPLY_MES = ""
            GoTo A
        End If

        If StrReceData(0) = "D" Then
            SendXieShuJu(MySocket, StrReceData)
        End If
        If StrReceData(0) = "7" Then
            Dim recdata() As String = StrReceData.Split(",")
            Todaycount.Screwcount += recdata(1)
            SNInfo.Screw_Qty = recdata(1)
            TextBox6.Text = Todaycount.Screwcount.ToString
            If TextBox1.Text = "0" Or TextBox6.Text = "0" Then
                TextBox7.Text = "100.00%"
                mainInfo.Yield = TextBox7.Text
            Else
                Dim NGFG As Integer = Val(TextBox3.Text) + Val(TextBox14.Text)
                Dim ng As Double = 100 * (1 - (Val(NGFG) / Val(TextBox6.Text)))
                TextBox7.Text = Format(ng, "0.00") & "%"
                mainInfo.Yield = TextBox7.Text
            End If
            Dim sendByte() As Byte = Encoding.ASCII.GetBytes("OK" & vbCrLf)
            MySocket.Send(sendByte)
            GoTo A
        End If

        '发送扭力、角度、供料器、禁用至机器人
        If StrReceData(0) = "8" Then
            If StrReceData(1) = "1" Then
                SendPointPara(MySocket, StrReceData)
            Else
                SendPointPara2(MySocket, StrReceData(1))
            End If
            GoTo A
        End If

        If StrReceData(0) = "s" Then
            If StrReceData(1) = "k" Then '锁附skip,M1,异常,漏锁
                Dim n As Integer = StrReceData.Split(",")(1)
                SNDetail.NumOfScrew = n
                If DataByPCS.IsOK = 1 Then
                    DataByPCS.IsOK = 0
                End If
                '
                'Suction = "u"
                'Flag = "S"
                '
                DataByPCS.Points(n - 1).NO = n 'point_NO
                DataByPCS.Points(n - 1).Result = "NG"
                SNDetail.Status = 1
                DataByPCS.Points(n - 1).NGReson = "SCR-C02001"
                Suction = "u"
                Flag = "K"
                Skip = CStr(n)
                PointResultShow("skip", n)
                '  MsgBox("第" & n & "颗漏锁！", MsgBoxStyle.OkOnly, "警告")
                SNDetail.ErrType = DataByPCS.Points(n - 1).NGReson
                SNDetail.Screw_A1 = "X,X,X,X"
                SNDetail.SF_Cdt_End = Format(DateTime.Now, "yyyyMMddHHmmss") & Format(DateTime.Now.Millisecond, "000")
                SNDetail.SF_Cdt_Begin = SNDetail.SF_Cdt_End
                upload_SNDetail()
                BadScrew = BadScrew + 1
                AddErrMsgToTextBox("第" & n & "颗漏锁！")
                'If newset(7) Then
                '    Dim AA As String = MES_SCADA_Warning("Produce", "SCR-C0003", "第" & n & "颗漏锁！")
                '    AppendInfoToTextBox("接收MES回传SCADA_SCADA_Warning信息：" & AA)
                '    Dim BB As String = MES_SCADA_Warning("Eliminate", "SCR-C0003", "第" & n & "颗漏锁！")
                '    AppendInfoToTextBox("接收MES回传SCADA_SCADA_Warning信息：" & BB)
                'End If
                GoTo A
            ElseIf StrReceData(1) = "e" Then '记录吐料几次     '单颗拍照,最多支持4 type 特征
                Todaycount2.SuctionCount = Todaycount2.SuctionCount + 1
                TextBox5.Text = Todaycount2.SuctionCount
                ThrowScrew = ThrowScrew + 1
                'Dim strReceString() As String = Split(StrReceData, ",")
                'If strReceString(1) = "1" Then
                '    AppendInfoToTextBox("auto1(MySocket, StrReceData)")
                '    SinglePointCameraProcess_1(MySocket, strReceString(2))
                '    GoTo A
                'End If
                'If strReceString(1) = "2" Then
                '    AppendInfoToTextBox("auto2(MySocket, StrReceData)")
                '    SinglePointCameraProcess_2(MySocket, strReceString(2))
                '    GoTo A
                'End If
                'If strReceString(1) = "3" Then
                '    AppendInfoToTextBox("auto2(MySocket, StrReceData)")
                '    SinglePointCameraProcess_3(MySocket, strReceString(2))

                '    GoTo A
                'End If
                'If strReceString(1) = "4" Then
                '    AppendInfoToTextBox("auto2(MySocket, StrReceData)")
                '    SinglePointCameraProcess_4(MySocket, strReceString(2))
                '    GoTo A
                'End If
            End If
        End If

        If StrReceData(0) = "a" Then
            StepOK2 = True
            If StrReceData(4) = "5" Then
                AppendInfoToTextBox("auto1(MySocket, StrReceData)")
                auto1(MySocket, StrReceData)
                GoTo A
            End If

            If StrReceData(4) = "6" Then
                AppendInfoToTextBox("auto2(MySocket, StrReceData)")
                auto2(MySocket, StrReceData)
                GoTo A
            End If
            GoTo A
        End If

        '写入自动匹配的拍照点
        If StrReceData(0) = "k" Then
            kill_InfoProcess(StrReceData)
            GoTo A
        End If

        If StrReceData(0) = "C" Then
            If StrReceData(1) = "Y" Then
                '总锁附结束
                Dim recdata() As String = StrReceData.Split("=")
                TextBox_CT.Text = Format(Val(recdata(1)), "0.00") & " s"
                endTime = DateTime.Now
                SNInfo.SF_Cdt_End = Format(DateTime.Now, "yyyyMMddHHmmss") & Format(DateTime.Now.Millisecond, "000")
                EndTimeID = Format(DateAndTime.Now, "yyyy-MM-dd HH:mm:ss")
                Dim SF_time As Double = 0
                SF_time = Math.Round(Val(Trim(recdata(1))), 1) 'Format(recdata(1), "0.0")
                Todaycount.SFTime += SF_time
                SFTime.Text = Format(Todaycount.SFTime, "0.0")
                ' upload_SNInfo()
                If BadScrew > 0 Then
                    ResultPASS = "Failed"
                End If

                If newset(7) Then '数据上传
                    If newset(7) And MesConectFlag Then
                        Try
                            Dim count As Integer = Val(TextBox1.Text) - Val(TextBox_PCSFailed.Text)
                            MesScrewWorkData.MAIN.SN = SNInputBox.Text
                            MesScrewWorkData.MAIN.BatchTimes = TextBox_Sycs.Text
                            MesScrewWorkData.MAIN.NozzleTimes = MesScrewWorkData.MAIN.BatchTimes
                            MesScrewWorkData.MAIN.Amount = TextBox1.Text
                            MesScrewWorkData.MAIN.CtCycle = TextBox_CT.Text
                            MesScrewWorkData.MAIN.OperatorName = TextBox_OPID.Text
                            MesScrewWorkData.MAIN.OKQty = count
                            AppendMESToTextBox(Method.MES_SCADA_ScrewWorkData(MesScrewWorkData))
                            MesScrewWorkData.MAIN.PointParameter.Clear()
                        Catch ex As Exception
                            AddErrMsgToTextBox(ex.Message.ToString())
                            MesConectFlag = False
                        End Try
                    End If
                End If

                Dim sendByte() As Byte = Encoding.ASCII.GetBytes("OK" & vbCrLf)
                MySocket.Send(sendByte)
                AppendInfoToTextBox("回复'OK'" + vbCrLf)
                If SN_Queue.Count > 0 Then
                    AppendInfoToTextBox(SN_Queue(0).sn & "生产结束。")
                    SN_Queue.Dequeue()
                    showSNQueueFlag = True
                End If
                SF_Fail_Qty_Single = 0
                SB_Fail_Qty_Single = 0
                SNPoint_X = ""
                SNPoint_Y = ""
                SNPoint_Z = ""
                LockScrew = 0
                BadScrew = 0
                ThrowScrew = 0
                EndTimeID = ""
                StartTimeID = ""
                PhotoFail = 0
                FloatHigh = 0
                ScrewLoose = 0
                ResultPASS = "PASS"
                SaveDeviation(Format(DateAndTime.Now, "yyyy-MM-dd HH:mm:ss"), TextBox_SN.Text, Chanpin, machineInfo.Line, machineInfo.Device_id, SNInfo.Status, TextBox_CT.Text)
            Else
                SN_Socket = MySocket
                NoProduct = True
            End If
            GoTo A
        End If
        If StrReceData(0) = "I" Then
            Dim recdata() As String = StrReceData.Split("=")
            SNInfo.SF_Cdt_Begin = Format(DateTime.Now, "yyyyMMddHHmmss") & Format(DateTime.Now.Millisecond, "000")
            Dim IDEL_time As Double = 0
            If startTime_SC <> DateTime.MinValue Then
                startTime = DateTime.Now
                IDEL_time = Format((startTime.Ticks - startTime_SC.Ticks) / 10000000, "0.0")
                Todaycount.IDELTime += IDEL_time
                'Todaycount.IDELTime = Format(Todaycount.IDELTime.ToString, "0.0")
                IDELTime.Text = Format(Todaycount.IDELTime, "0.0")
                startTime_SC = DateTime.MinValue
            Else
                IDEL_time = Math.Round(Val(Trim(recdata(1))), 1) 'Format(recdata(1), "0.0")
                Todaycount.IDELTime += IDEL_time
                IDELTime.Text = Format(Todaycount.IDELTime, "0.0")
            End If
            GoTo A
        End If

        If StrReceData(0) = "E" Then    '异常台数记录flag
            IsScrewFail = True
            GoTo A
        End If

        If StrReceData(0) = "B" Then    'idle Time设置
            AppendInfoToTextBox(vbCrLf & "IdleTime: " & IDLETime.ToString & " 秒" & vbCrLf)
            Dim byteSend As Byte() = Encoding.ASCII.GetBytes((IDLETime * 1000) & vbCrLf)
            MySocket.Send(byteSend)
            GoTo A
        End If

        If StrReceData(0) = "P" Then
            Dim sendByte() As Byte = Encoding.ASCII.GetBytes("OK" & vbCrLf)
            MySocket.Send(sendByte)
            P_InfoProcess(StrReceData)
            GoTo A
        End If

        '接收拍照点坐标
        If StrReceData(0) = "X" Then
            photoToRobot(MySocket, StrReceData)
            GoTo A
        End If

        '是否启用Q程序
        If StrReceData(0) = "Q" Then
            MesScrewWorkData.MAIN.PointParameter.Clear()
            Dim s() As String = StrReceData.Split(",")
            If s(1) = "1" Then
                SN_Queue.Clear()
                showSNQueueFlag = True
                If newset(0) = True Then '扫码切换模板
                    Can_Barcode = True
                Else
                    Can_Barcode = False
                End If
                Dim byteSend As Byte() = Encoding.ASCII.GetBytes(CStr(AddProdflag) + vbCrLf)
                If AddProdflag = True Then
                    AppendInfoToTextBox("进入制作产品模板程序")
                Else
                    AppendInfoToTextBox("进入生产产品程序")
                End If
                AppendInfoToTextBox(AddProdflag)
                MySocket.Send(byteSend)
            ElseIf s(1) = "2" Then
                Dim byteSend As Byte() = Encoding.ASCII.GetBytes(Motor_dly.ToString + vbCrLf)
                AppendInfoToTextBox(Motor_dly.ToString + vbCrLf)
                MySocket.Send(byteSend)
            ElseIf s(1) = "3" Then
                Dim byteSend As Byte() = Encoding.ASCII.GetBytes(CStr(AddProdflag1) + vbCrLf)
                If AddProdflag1 = True Then
                    AppendInfoToTextBox("进入扭力测试程序")
                Else
                    AppendInfoToTextBox("进入生产产品程序")
                End If
                AppendInfoToTextBox(AddProdflag1)
                MySocket.Send(byteSend)
                AddProdflag1 = False
                Button5.BackColor = Color.White
            End If

            GoTo A
        End If

        'MANUAL 位置
        If StrReceData(0) = "m" Then
            Dim ss As String = StrReceData.Split(",")(1)
            If ss = "STEP1" Then
                StepOK1 = True
                CallRobotProgram("complete")
            ElseIf ss = "STEP2" Then
                CallRobotProgram("complete")
            End If
            'If ss = "outfirst" Then
            '    Vision_NG = "FIRST"
            'ElseIf ss = "outseccond" Then
            '    Vision_NG = "SECOND"
            'End If

            GoTo A
        End If

        '初始化
        If StrReceData(0) = "S" Then
            If StrReceData(1) = "C" Then
                MesScrewWorkData.MAIN.PointParameter.Clear()
                CurNameAndSN.ChanpinName = ""
                CurNameAndSN.ChanpinSN = ""
                startTime_SC = DateTime.Now
                Flag = "C"
                'connectRobot()
                isFail = True

c:
                If Flag = "InitProOver" Then
                    RobotParameterSet(MySocket, StrReceData)
                Else
                    GoTo c
                End If
                GoTo A
            End If

        End If
        If StrReceData(0) = "M" Then
            '设备状态
            If StrReceData(1) = "S" Then
                Dim recdata() As String = StrReceData.Split(",")
                If recdata(1) = "ShutDown" Then
                    If startTime_SD = DateTime.MinValue Then
                        startTime_SD = DateTime.Now
                    End If
                    'If recdata(2) <> "" Then
                    If recdata(2)(4) = "E" Then '机器人err Code 9位
                        If recdata(2).Length < 9 Then
                            Dim Lefrecd As String = Mid(recdata(2), 1, 5)
                            Dim Rightrecd As String = Mid(recdata(2), 6, recdata(2).Length - 1)
                            Dim midZero As String = ""
                            For i = recdata(2).Length + 1 To 9
                                midZero = midZero & "0"
                            Next
                            recdata(2) = Lefrecd & midZero & Rightrecd
                        End If
                        TextBox_RBErr.Text = StrReceData
                        AddErrMsgToTextBox("机器人异常！")
                        'If newset(7) Then
                        '    Dim AA As String = MES_SCADA_Warning("Produce", "SCR-C0000", "机器人异常！")
                        '    AppendInfoToTextBox("接收MES回传SCADA_SCADA_Warning信息：" & AA)
                        '    Dim BB As String = MES_SCADA_Warning("Eliminate", "SCR-C0000", "机器人异常！")
                        '    AppendInfoToTextBox("接收MES回传SCADA_SCADA_Warning信息：" & BB)
                        'End If
                    Else    '自定义err Code 10 位--机器人修正
                        'If recdata(2).Length < 10 Then
                        '    Dim Lefrecd As String = Mid(recdata(2), 1, 5)
                        '    Dim Rightrecd As String = Mid(recdata(2), 6, recdata(2).Length - 1)
                        '    Dim midZero As String = ""
                        '    For i = recdata(2).Length + 1 To 10
                        '        midZero = midZero & "0"
                        '    Next
                        '    recdata(2) = Lefrecd & midZero & Rightrecd
                        'End If
                    End If
                    'If recdata(1) = "Run" Then
                    '    DataByReal.Errcode = Nothing
                    'Else
                    'If recdata(2) = "SCR-E0050" Or recdata(2) = "SCR-E0051" Then
                    '    recdata(2) = "SCR-C01001"
                    '    AddErrMsgToTextBox("急停触发！")
                    '    'Else
                    '    '    DataByReal.Errcode = recdata(2)
                    'End If
                    'End If
                    'Else
                    '    DataByReal.Errcode = Nothing
                    'End If
                    TextBox_RunStatus.Text = "ShutDown"
                    TextBox_RunStatus.BackColor = Color.Red
                    machineInfoStatus.Status = "2"
                    ErrorCode.Text = recdata(2)
                    ErrorCode.BackColor = Color.Red
                    machineInfoStatus.ErrorCode = recdata(2)
                    StatusRun = "Stop"
                    If newset(7) Then
                        'Dim SFData2 As String = MES_SCADA_StatusChange(StatusRun)
                        'AppendInfoToTextBox("接收MES回传SCADA_StatusChange信息：" & SFData2)
                    End If
                    StatusRun = ""
                    'uploadstate()
                End If
                GoTo A
            End If
            '单颗锁附结果
            Try
                If StrReceData(1) = "R" Then
                    Dim recdata() As String = StrReceData.Split(",")
                    SNDetail.NumOfScrew = recdata(1)
                    Dim n As Integer = Val(recdata(1))
                    If recdata(2) = "OK" Then
                        SNDetail.Status = "OK"
                        'If ZaxisCheckUSE = True Then    '启用Z轴检测
                        '    Dim ZaxisCheckOK As Boolean = ZaxisCheck(AxActUtlType1, n)   'z轴判断
                        '    If ZaxisCheckOK = False Then    'Z轴圈数未达到，浮锁
                        '        DataByPCS.Points(n - 1).Result = "NG"
                        '        SNDetail.Status = 1
                        '        recdata(3) = "SCR-C02002"
                        '        If DataByPCS.IsOK = 1 Then
                        '            DataByPCS.IsOK = 0
                        '        End If
                        '        Flag = "S"
                        '        Suction = ""
                        '        Screw = n
                        '    Else    '正常锁附
                        '        ScrewOKCount += 1
                        '        DataByPCS.Points(n - 1).NGReson = Nothing
                        '    End If
                        'Else    '不启用z轴检查
                        '    ScrewOKCount += 1
                        '    DataByPCS.Points(n - 1).NGReson = Nothing
                        'End If
                        ScrewOKCount += 1
                        DataByPCS.Points(n - 1).NGReson = Nothing
                    ElseIf recdata(2) = "NG" Then
                        SNDetail.Status = "NG"
                        SNInfo.Status = "NG"
                        DataByPCS.Points(n - 1).Result = recdata(2)
                        If DataByPCS.IsOK = 1 Then
                            DataByPCS.IsOK = 0
                        End If
                        Flag = "S"
                        Suction = ""
                        BadScrew = BadScrew + 1
                        ScrewLoose = ScrewLoose + 1
                        AddErrMsgToTextBox("第" & Screw & "颗锁附失败！")

                    ElseIf recdata(2) = "HeightNG" Then
                        SNDetail.Status = "NG"
                        SNInfo.Status = "NG"
                        DataByPCS.Points(n - 1).Result = recdata(2)
                        If DataByPCS.IsOK = 1 Then
                            DataByPCS.IsOK = 0
                        End If
                        Flag = "S"
                        Suction = "H"
                        BadScrew = BadScrew + 1
                        ScrewLoose = ScrewLoose + 1
                        AddErrMsgToTextBox("第" & Screw & "颗锁附失败,浮高！")

                    End If
                    'PointResultShow(DataByPCS.Points(n - 1).Result, n)
                    'SNDetail.ErrType = recdata(3)
                    'SNDetail.Screw_A1 = recdata(4) & "," & recdata(5) & "," & recdata(6) & "," & recdata(7)
                    'SNDetail.SF_Cdt_End = Format(DateTime.Now, "yyyyMMddHHmmss") & Format(DateTime.Now.Millisecond, "000")
                    ' upload_SNDetail()
                    Screw = n
                    SNDetail.ErrType = recdata(3)
                    SNDetail.SF_Cdt_End = DateTime.Now
                    Torsion = ReadDeviceRandom_Date("D126") / 1000
                    Dim Float_H As Double = 0 'ReadDeviceRandom_Date("D370")
                    Dim time10 As String = Format((Val(SNDetail.SF_Cdt_End) - Val(SNDetail.SF_Cdt_Begin)) / 10000000, "0.0")
                    MesScrewCT = time10
                    ScrewtoAccess(TextBox_SN.Text, Format(DateAndTime.Now, "yyyy-MM-dd HH:mm:ss"), CurScrewPara.PointCount & "—" & Screw, Chanpin, Torsion & "N.M", Float_H, time10 & "s", machineInfo.Device_id, SNDetail.Status)
                    Dim sendByte() As Byte = Encoding.ASCII.GetBytes("OK" & vbCrLf)
                    MySocket.Send(sendByte)
                    GoTo A
                End If
            Catch ex As Exception
                AddErrMsgToTextBox(ex.StackTrace.ToString & vbCrLf & ex.Message.ToString)
            End Try

            '单颗锁附开始
            If StrReceData(1) = "A" Then
                LockScrew = LockScrew + 1
                SNDetail.SF_Cdt_Begin = DateTime.Now
                Dim sendByte() As Byte = Encoding.ASCII.GetBytes("OK" & vbCrLf)
                MySocket.Send(sendByte)
                GoTo A
            End If
            '单颗锁附结束
            'If StrReceData(1) = "B" Then

            '    GoTo A
            'End If
        End If
        '浮高
        If StrReceData(0) = "F" Then
            Dim recdata() As String = StrReceData.Split(",")
            Dim Float_H As Double = Val(ZaxisPls(Val(recdata(1))))
            AppendInfoToTextBox(vbCrLf + "浮高:" & Float_H)
            WriteDeviceRandom_Torsion("D358", Float_H * 200)
            Dim sendByte() As Byte = Encoding.ASCII.GetBytes("OK" & vbCrLf)
            MySocket.Send(sendByte)
            AppendInfoToTextBox(vbCrLf + "浮高:" & "OK")
        End If
        '扭力
        If StrReceData(0) = "N" Then
            Dim recdata() As String = StrReceData.Split(",")
            Torsion2 = Val(recdata(1))
            SNDetail.TorqueValue = Torsion2.ToString
            AppendInfoToTextBox(vbCrLf + "扭力:" & Torsion2 & "kgf.cm")
            '''''''''''''''''''''''''''''''''''三菱PLC发送方式
            WriteDeviceRandom_Torsion("D933", Torsion2 * 100)
            ''''''''''''''''''''''''''''''''''西门子发送数据方式
            'Torsion2 = Torsion2 * 1000
            'Dim Torsion_n(10) As String
            'Torsion_n(0) = CStr(Torsion2)
            'SIEMENS_PLC_butWrite("V", "1000", "1", "W_INT16", Torsion_n)
            ''''''''''''''''''''''''
            Dim sendByte() As Byte = Encoding.ASCII.GetBytes("OK" & vbCrLf)
            MySocket.Send(sendByte)
            GoTo A
        End If

        If StrReceData(0) = "R" Then
            Dim recdata() As String = StrReceData.Split(",")
            Angle2 = recdata(1)
            'AppendInfoToTextBox(vbCrLf + "角度:" & Angle2 & "C°")
            'WriteDeviceRandom_Angle(AxActUtlType1)
            'Dim Angle_n(10) As String
            'Angle_n(0) = CStr(recdata(1))
            AppendInfoToTextBox(vbCrLf + "角度:" & Angle2 & "C°")

            'SIEMENS_PLC_butWrite("V", "1148", "1", "D_REAL32", Angle_n)
            WriteDeviceRandom_Torsion("D254", Angle2 * 10)

            Dim sendByte() As Byte = Encoding.ASCII.GetBytes("OK" & vbCrLf)
            MySocket.Send(sendByte)
            AppendInfoToTextBox(vbCrLf + "回传：" & "OK")
            GoTo A
        End If

        '每颗锁附结果"result,1,OK,X,Y,Z,R,"
        If StrReceData(0) = "r" Then
            ' DataByReal.Errcode = Nothing
            Dim recdata() As String = StrReceData.Split(",")
            Dim n As Integer = Val(recdata(1))
            DataByPCS.Points(n - 1).NO = n 'point_NO
            DataByPCS.Points(n - 1).Result = recdata(2)
            DataByPCS.Points(n - 1).ScrewPositionX = Val(recdata(3))
            DataByPCS.Points(n - 1).ScrewPositionY = Val(recdata(4))
            DataByPCS.Points(n - 1).ScrewPositionZ = Val(recdata(5))
            DataByPCS.Points(n - 1).ScrewPositionR = Val(recdata(6))

            If DataByPCS.Points(n - 1).Result = "NG" Then   '扭力未达到
                DataByPCS.Points(n - 1).NGReson = "SCR-C02001"
                If DataByPCS.IsOK = 1 Then
                    DataByPCS.IsOK = 0
                End If
                Flag = "S"
                Suction = ""
                Screw = n

                AddErrMsgToTextBox("第" & Screw & "颗锁附失败！")
            Else

                'If ZaxisCheckUSE = True Then    '启用Z轴检测
                '    Dim ZaxisCheckOK As Boolean = ZaxisCheck(AxActUtlType1, n)   'z轴判断
                '    If ZaxisCheckOK = False Then    'Z轴圈数未达到，浮锁
                '        DataByPCS.Points(n - 1).Result = "NG"
                '        DataByPCS.Points(n - 1).NGReson = "SCR-C02002"
                '        If DataByPCS.IsOK = 1 Then
                '            DataByPCS.IsOK = 0
                '        End If
                '        Flag = "S"
                '        Suction = ""
                '        Screw = n
                '    Else    '正常锁附
                '        ScrewOKCount += 1
                '        DataByPCS.Points(n - 1).NGReson = Nothing
                '    End If
                'Else    '不启用z轴检查
                '    ScrewOKCount += 1
                '    DataByPCS.Points(n - 1).NGReson = Nothing
                'End If
                ScrewOKCount += 1
                DataByPCS.Points(n - 1).NGReson = Nothing
            End If
            PointResultShow(DataByPCS.Points(n - 1).Result, n)
            GoTo A
        End If

        '报警信息处理
        If StrReceData(0) = "A" Then
            Dim byteAlarmInfo(50) As Char
            If StrReceData(7) = "r" Then

                AddErrMsgToTextBox("供料器指定错误或无螺丝锁附！请确认后重新复机")
                GoTo Information
            End If

            'If StrReceData(2) = "S" Then
            '    If StrReceData(9) = "u" Then
            '        Suction = StrReceData(9)
            '    Else
            '        Suction = ""
            '        Screw = StrReceData(7)
            '    End If
            '    Flag = "S"
            '    GoTo Information
            'End If
            If StrReceData(2) = "V" Then  '视觉识别失败
                PhotoFail = PhotoFail + 1
            End If

            If StrReceData(2) = "C" Then  '视觉识别失败

                Flag = "V"
                AddErrMsgToTextBox("拍照失败！")
                GoTo Information
            End If

Information:
            StrReceData.CopyTo(1, byteAlarmInfo, 0, 50)
            strAlarmInfo = byteAlarmInfo
            AppendInfoToTextBox("报警信息:" + strAlarmInfo + vbCrLf)
            If strAlarmInfo.Contains("Screw1") Then
                AddErrMsgToTextBox(("报警信息:1#供料器取螺丝失败"))
            ElseIf strAlarmInfo.Contains("Screw2") Then
                AddErrMsgToTextBox(("报警信息:2#供料器取螺丝失败"))
            ElseIf strAlarmInfo.Contains("Screw3") Then
                AddErrMsgToTextBox(("报警信息:3#供料器取螺丝失败"))
            ElseIf strAlarmInfo.Contains("Screw4") Then
                AddErrMsgToTextBox(("报警信息:4#供料器取螺丝失败"))
            ElseIf strAlarmInfo.Contains("Emergency") Then
                AddErrMsgToTextBox(("报警信息:机械手急停" + vbCrLf))
            ElseIf strAlarmInfo.Contains("Feeder1") Then
                AddErrMsgToTextBox(("报警信息:1#供料器取螺丝无螺丝，请添加螺丝"))
            ElseIf strAlarmInfo.Contains("Feeder2") Then
                AddErrMsgToTextBox(("报警信息:2#供料器取螺丝无螺丝，请添加螺丝"))
            ElseIf strAlarmInfo.Contains("Feeder3") Then
                AddErrMsgToTextBox(("报警信息:3#供料器取螺丝无螺丝，请添加螺丝"))
            ElseIf strAlarmInfo.Contains("Feeder4") Then
                AddErrMsgToTextBox(("报警信息:4#供料器取螺丝无螺丝，请添加螺丝"))
            End If

        End If

A:

    End Sub

    Protected Sub AddInfoToInfoTextBox(ByVal s As String)
        If (TxtResult1.InvokeRequired) Then
            Dim cb As AddRecvToText = New AddRecvToText(AddressOf AddInfoToInfoTextBox)
            Invoke(cb, s)
        Else
            ' TxtResult1.AppendText(s + vbCrLf)
            TxtResult1.Text = s + vbCrLf
        End If
    End Sub

    Private Sub initParam() '初始化参数

        gProDataPath = DebugPath & "\tool"
        gIsRun = True
        TSGrabContinues1.Enabled = False
        'TSGrabContinues2.Enabled = False
        'TSGrabContinues3.Enabled = False
        'TSGrabContinues4.Enabled = False
        'TSIsRun.BackColor = Color.Green
        产品管理ProductToolStripMenuItem.Enabled = False
        设置ToolStripMenuItem.Enabled = False
        Count_Clear.Enabled = False
        ToolStripButton17.Enabled = False
        '  TestToolStripMenuItem.Enabled = False
        '   TxtScrewIndex1.ReadOnly = False
        gIsModBus = False
        gCurrProName = GetSetting("XCPro", "Settings", "当前产品", "") '当前产品
        gUserTime = GetSetting("XCPro", "Settings", "UserTimes", "-1") ' 剩余使用天数
        gVisionFailedPath = GetSetting("XCPro", "Settings", "VisionFailedPath", "D:\VisionFailed\") ' 视觉失败图像保存路径
        TextBox4.Text = gVisionFailedPath
        If gUserTime <= -1 Then
            SaveSetting("XCPro", "Settings", "UserTimes", "90")
        End If
        'If gUserTime = 0 Then
        '    gUserTime += 1
        '    MsgBox("超过试用期限！")

        '    ' FrmMaintainace.ShowDialog()
        '    '  Me.Close()
        'End If
        'If gUserTime Mod 10 = 1 Then
        '    Dim pwd As String = ""
        '    MsgBox("设备到达维护时间，请维护后再使用！")
        '    ' FrmMaintainace.ShowDialog()
        'End If
        If gCurrProName <> "" Then
            TCmbPro.Items.Add(gCurrProName)
            TCmbPro.SelectedItem = gCurrProName
        End If
        ' TSIsRun.BackColor = Color.Green
        gCheckIndex = 1

    End Sub

    'Private Sub Open_Click_PLC()    '角度初始化

    '    Dim iReturnCode As Integer              'Return code
    '    Dim iLogicalStationNumber As Integer = 1    'LogicalStationNumber for ActUtlType

    '    Try
    '        'Set the value of 'LogicalStationNumber' to the property.
    '        AxActUtlType1.ActLogicalStationNumber = iLogicalStationNumber

    '        'The Open method is executed.
    '        iReturnCode = AxActUtlType1.Open()
    '        AppendInfoToTextBox("btn_Open_Click")
    '        If iReturnCode = 0 Then
    '            'When the Open method is succeeded, disable the TextBox of 'LogocalStationNumber'.
    '            AppendInfoToTextBox("Open_Click_PLC_OK")
    '        Else
    '            AppendInfoToTextBox("Open_Click_PLC_Failed")
    '        End If

    '    Catch exception As Exception
    '        'Exception processing
    '        AppendInfoToTextBox("Open_Click_PLC:" & exception.Message.ToString)
    '        Exit Sub
    '    End Try

    'End Sub

    Function FindAlarmInfo(ByVal alarmNum As String) As String
        Dim AlarmInfo As String = ""
        For i = 0 To AlarmObject.Count
            If (alarmNum = CType(AlarmObject.Item(i), AlarmInfo).AlarmNum) Then
                AlarmInfo = CType(AlarmObject.Item(i), AlarmInfo).AlarmInformation
                Return AlarmInfo
            End If
        Next
        Return AlarmInfo
    End Function

    Public Sub initPro(ByVal ProName As String) '初始化产品参数
        Chanpin = ProName
        Try
            GetXML()
            TSProcessLoad.Value = 0
            Dim path As String = gProDataPath & "\" & ProName & "\"
            For i = 0 To Cam_num - 1
                gTBCheck(i) = Nothing
                gTBCheck(i) = New CogToolBlock
            Next

            If Dir(path, FileAttribute.Directory) <> "" Then '如果路径存在
                For i = 0 To Cam_num - 1
                    gTBCheck(i) = CogSerializer.LoadObjectFromFile(path & "TBCheck" & (i + 1).ToString & ".vpp")
                    gTBCheck(i).LastRunRecordEnable = Cognex.VisionPro.Implementation.Internal.CogUserToolLastRunRecordConstants.CompositeSubToolRecords
                    TSProcessLoad.Value += Int(100 / Cam_num)
                Next

                WriteInspecLog(TSLog, "加载产品完成" & vbTab & ProName) '错误信息写入log
                Dim WX As String = TSLog.Text
                Dim WJX() As String = WX.Split(vbTab)
                SaveSetting("XCPro", "Settings", "当前产品", ProName)
                Me.Text = "视觉检测系统"
                GetDirectFiles(gProDataPath)
                TCmbPro.SelectedItem = ProName
                Chanpin = ProName

                '数据上传
                'DataByPCS.Program = Chanpin
                'DataByReal.Program = Chanpin
                'DataByReal.Model = Chanpin
                'CurNameAndSN.ChanpinName = Chanpin
                'CurNameAndSN.ChanpinSN = NewNameAndSN.ChanpinSN 'SN扫码
                'DataByPCS.USN = CurNameAndSN.ChanpinSN
            Else
                WriteInspecLog(TSLog, "加载产品路径不存在") '错误信息写入log
            End If
            ToolStripButton17.Enabled = True
            TSProcessLoad.Value = 0
            'initPointModel(Chanpin)
        Catch ex As Exception
            MsgBox("初始化加载产品出错!" & ex.Message)
            WriteInspecLog(TSLog, "初始化加载产品出错" & vbTab & ex.Message & ex.StackTrace) '错误信息写入log
            ToolStripButton17.Enabled = True
        End Try
    End Sub

#End Region

#Region "图像处理函数"

    Private Sub FirstCameraImageProcess(ByRef MySocket As Socket, ByVal StrReceData As String)
        Dim __time As DateTime = DateTime.Now
        AppendInfoToTextBox("Dim i As Integer")

        Try
            Dim tmpfifo0 As CogAcqFifoTool = gTBCheck(0).Tools.Item("相机设定")
            Dim tmpCalibCB As CogCalibCheckerboardTool = gTBCheck(0).Tools.Item("CogCalibCheckerboardTool1")
            Dim tmpCogCalibCheckerboardTool As CogCalibNPointToNPointTool = gTBCheck(0).Tools.Item("CogCalibNPointToNPointTool1")
            Dim tmpPmalign1 As CogPMAlignTool = gTBCheck(0).Tools.Item("CogPMAlignTool1")
            Dim CogIPOneImageTool1 As CogIPOneImageTool = gTBCheck(0).Tools.Item("CogIPOneImageTool1")
            ' Dim tmpPmalign3 As CogPMAlignTool = gTBCheck(0).Tools.Item("CogPMAlignTool3")
            Dim tmpPmalign As CogPMAlignTool = tmpPmalign1
            Dim strErrorInfo As String = ""
            Dim strSendData As String = ""
            Dim bHasObject As Boolean = False
            If tmpfifo0.Operator.FrameGrabber IsNot Nothing Then
                AppendInfoToTextBox("FrameGrabber")
                If True Then
                    'If tmpfifo0.Operator.FrameGrabber.SerialNumber = SecondCCDSerNum Then
                    tmpfifo0.Run()
                    tmpfifo0.Run()
                    If tmpfifo0.OutputImage Is Nothing Then
                        AppendInfoToTextBox(tmpfifo0.RunStatus.Exception.ToString)
                        AppendInfoToTextBox(tmpfifo0.RunStatus.Message)
                        tmpfifo0.Run()
                        AppendInfoToTextBox("AcqBaseImage首次取相失败，再进行第二次取相")
                        If tmpfifo0.OutputImage Is Nothing Then
                            SecondCCDState = 2
                            GoTo c
                        Else
                            GoTo sucess
                        End If
                    Else
sucess:
                        If tmpfifo0.OutputImage IsNot Nothing Then
                            SecondCCDState = 0 '正常
                            AppendInfoToTextBox("tmpCalibCB.Run()")
                            CogIPOneImageTool1.Run()
                            tmpCalibCB.Run()
                            tmpCogCalibCheckerboardTool.Run()
                            tmpPmalign1.Run()
                            'tmpPmalign2.Run()
                            ' tmpPmalign3.Run()
                            Dim dTemp As Double = 0
                            Dim dTemp2 As String = ""
                            If tmpPmalign1.RunStatus.Result = CogToolResultConstants.Accept Then

                                If tmpPmalign.Results.Count > 0 Then
                                    dTemp = tmpPmalign.Results.Item(0).GetPose.TranslationX.ToString
                                    dTemp2 = Format(dTemp, "000.00")
                                    SendDataX(0) = dTemp
                                    strSendData += dTemp2 & ","
                                    dTemp = tmpPmalign.Results.Item(0).GetPose.TranslationY.ToString
                                    dTemp2 = Format(dTemp, "000.00")
                                    SendDataY(0) = dTemp
                                    strSendData += dTemp2 & ","
                                    dTemp = 0
                                    dTemp += tmpPmalign.Results.Item(0).GetPose.Rotation / Acos(-1) * 180
                                    dTemp2 = Format(dTemp, "000.00")
                                    SendDataR(0) = dTemp
                                    AppendInfoToTextBox(" SendDataR(0) = dTemp")
                                    strSendData += dTemp2 & ","
                                    DataByPCS.CameraoffsetX = tmpPmalign.Results.Item(0).GetPose.TranslationX
                                    DataByPCS.CameraoffsetY = tmpPmalign.Results.Item(0).GetPose.TranslationY
                                Else
                                    strSendData += "999" + ","
                                    strSendData += "999" + ","
                                    strSendData += "229.9,"
                                    strSendData += "0"
                                    SendDataX(0) = 999999.0
                                    DataByPCS.CameraoffsetX = 999
                                    DataByPCS.CameraoffsetY = 999
                                End If

                                If tmpPmalign.Results.Count < 1 Then
                                    Dim timeNowUTC As String = Format((DateTime.UtcNow - New DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalSeconds * 1000, "00")
                                    'SN_UTC.jpg
                                    Dim fileName As String = Format(Date.Now.Date, "yyyyMMdd") & Format(DateTime.Now.Ticks) & ".jpg"
                                    ' Dim filePath As String = gVisionFailedPath & TCmbPro.Text & "\" & Format(Date.Now.Date, "yyyyMMdd") & "\" & Chanpin & "\" & "Fail Image\"
                                    Dim filePath As String = gVisionFailedPath & Format(Date.Now.Date, "yyyyMMdd") & "\" & Chanpin & "\" & "Fail Image\"

                                    YSPic(CogRecordDisplay2, CogIPOneImageTool1, filePath, fileName)
                                End If
c:
                                If SecondCCDState = 2 Then
                                    strSendData += "999,999,0,0"
                                    SendDataX(0) = 999999.0
                                End If
                            Else
                                strSendData += "999,0,0,0"
                                SendDataX(0) = 999999.0
                            End If
                            strSendData += "" ' vbCrLf
                            AppendInfoToTextBox("1:" & vbCrLf & strSendData + vbCrLf)
                            strSendData = "" ' vbCrLf
                            'strSendData += CStr(Pget(6).YPosCompensate) + "," + CStr(Todaycount.PassCount) + "," + CStr(Retry_Times) + ","
                            'strSendData += CStr(Pget(0).XPosCompensate) + "," + CStr(Pget(0).YPosCompensate) + "," + CStr(Pget(0).ZPosCompensate) + ","
                            'strSendData += CStr(Pget(1).XPosCompensate) + "," + CStr(Pget(1).YPosCompensate) + "," + CStr(Pget(1).ZPosCompensate) + ","
                            'strSendData += CStr(Pget(4).XPosCompensate) + "," + CStr(Pget(4).YPosCompensate) + "," + CStr(Pget(4).ZPosCompensate) + ","
                            'strSendData += CStr(Pget(5).XPosCompensate) + "," + CStr(Pget(5).YPosCompensate) + "," + CStr(Pget(5).ZPosCompensate) + "," + vbCrLf
                            'Dim byteSend As Byte() = Encoding.ASCII.GetBytes(strSendData)   '拍照点偏移、$拍照点合格计数、$从新拍照次数
                            'MySocket.Send(byteSend)

                            TSRest.Text = (DateTime.Now.Ticks - __time.Ticks) / 10000 & "ms"

                            CogRecordDisplay2.Image = CogIPOneImageTool1.OutputImage

                            CogRecordDisplay2.Fit()
                            If tmpfifo0.Operator.FrameGrabber IsNot Nothing Then
                                CogRecordDisplay2.Record = tmpPmalign.CreateLastRunRecord
                            End If
                        Else
                            SecondCCDState = 3
                        End If

                    End If
                Else
                    SecondCCDState = 1
                End If
            Else
                SecondCCDState = 2
                GoTo c
                AppendInfoToTextBox("未连接摄像机！")
            End If
        Catch ex As Exception
            WriteInspecLog(TSLog, "SecondCameraImageProcess" & vbTab & ex.StackTrace.ToString)
            MsgBox(ex.StackTrace.ToString & vbCrLf & ex.Message.ToString)

        End Try
        'CadToRobot()

d:
    End Sub

    Private Sub SecondCameraImageProcess(ByRef MySocket As Socket, ByVal StrReceData As String)
        Dim __time As DateTime = DateTime.Now
        AppendInfoToTextBox("SecondCameraImageProcess Run")
        Dim ReturnXYR As returnXY
        Try
            Dim tmpfifo0 As CogAcqFifoTool = gTBCheck(1).Tools.Item("相机设定")
            Dim tmpCalibCB As CogCalibCheckerboardTool = gTBCheck(1).Tools.Item("CogCalibCheckerboardTool1")
            Dim tmpCogCalibCheckerboardTool As CogCalibNPointToNPointTool = gTBCheck(1).Tools.Item("CogCalibNPointToNPointTool1")
            Dim tmpPmalign1 As CogPMAlignTool = gTBCheck(1).Tools.Item("CogPMAlignTool1")
            Dim CogIPOneImageTool1 As CogIPOneImageTool = gTBCheck(1).Tools.Item("CogIPOneImageTool1")

            Dim tmpPmalign As CogPMAlignTool = tmpPmalign1
            Dim strErrorInfo As String = ""
            Dim strSendData As String = ""
            Dim bHasObject As Boolean = False
            If tmpfifo0.Operator.FrameGrabber IsNot Nothing Then
                AppendInfoToTextBox("FrameGrabber")
                If True Then
                    'If tmpfifo0.Operator.FrameGrabber.SerialNumber = SecondCCDSerNum Then
                    tmpfifo0.Run()
                    If tmpfifo0.OutputImage Is Nothing Then
                        AppendInfoToTextBox(tmpfifo0.RunStatus.Exception.ToString)
                        AppendInfoToTextBox(tmpfifo0.RunStatus.Message)
                        tmpfifo0.Run()
                        AppendInfoToTextBox("AcqBaseImage首次取相失败，再进行第二次取相")
                        If tmpfifo0.OutputImage Is Nothing Then
                            SecondCCDState = 2
                            GoTo c
                        Else
                            GoTo sucess
                        End If
                    Else
sucess:
                        If tmpfifo0.OutputImage IsNot Nothing Then
                            AppendInfoToTextBox("ForthCameraImageProcess tmpCalibCB.Run()")
                            SecondCCDState = 0 '正常
                            CogIPOneImageTool1.Run()
                            tmpCalibCB.Run()
                            tmpCogCalibCheckerboardTool.Run()
                            tmpPmalign1.Run()
                            Dim dTemp As Double = 0
                            Dim dTemp2 As String = ""
                            If tmpPmalign1.RunStatus.Result = CogToolResultConstants.Accept Then

                                If tmpPmalign.Results.Count > 0 Then
                                    dTemp = tmpPmalign.Results.Item(0).GetPose.TranslationX.ToString
                                    dTemp2 = Format(dTemp, "000.00")
                                    SendDataX(2) = dTemp
                                    strSendData += dTemp2 & ","
                                    dTemp = tmpPmalign.Results.Item(0).GetPose.TranslationY.ToString
                                    dTemp2 = Format(dTemp, "000.00")
                                    SendDataY(2) = dTemp
                                    strSendData += dTemp2 & ","

                                    dTemp = 0
                                    dTemp += tmpPmalign.Results.Item(0).GetPose.Rotation / Acos(-1) * 180
                                    dTemp2 = Format(dTemp, "000.00")
                                    SendDataR(2) = dTemp
                                    AppendInfoToTextBox("SendDataR(2) = dTemp")
                                    strSendData += dTemp2 & ","
                                Else
                                    SendDataX(2) = 99999
                                End If
                                If tmpPmalign.Results.Count < 1 Then

                                    Dim timeNowUTC As String = Format((DateTime.UtcNow - New DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalSeconds * 1000, "00")
                                    Dim fileName As String = Format(Date.Now.Date, "yyyyMMdd") & Format(DateTime.Now.Ticks) & ".jpg"
                                    DataByPCS.NGPICNO = fileName
                                    Dim filePath As String = gVisionFailedPath & Format(Date.Now.Date, "yyyyMMdd") & "\" & Chanpin & "\" & "Fail Image\"
                                    YSPic(CogRecordDisplay4, CogIPOneImageTool1, filePath, fileName)

                                End If

c:

                                If SecondCCDState = 2 Then
                                    strSendData += "999,0,0,0"
                                    SendDataX(2) = 99999
                                End If
                            Else
                                strSendData += "999,0,0,0"
                                SendDataX(2) = 99999
                            End If
                            AppendInfoToTextBox("4:" + vbCrLf + strSendData + vbCrLf)
                            '读取CAD转换为机器人点位的坐标
                            Dim sql As String = "select * from robot_point where Product='" & Chanpin & "'" '产品表单模板名字'产品表单模板名字"
                            'da = New OleDbDataAdapter(sql, cn)
                            ds = New DataSet
                            ds = SearchMysql(sql)
                            'DataGridView1.DataSource = ds.Tables(0)
                            For w = 0 To 29
                                Dim k As Integer = 2 * (w + 4)
                                Dim m As Integer = 2 * w
                                pointCAD(k) = Val(ds.Tables(0).Rows(w)(2))
                                pointCAD(k + 1) = Val(ds.Tables(0).Rows(w)(3))
                                pointCAD_Z(w) = Val(ds.Tables(0).Rows(w)(4))
                                pointCAD_Z(w) += Pset(w).ZPosCompensate
                                pointCAD_C(w) = Val(ds.Tables(0).Rows(w)(5))
                                pointCAD_C(w) += Pset(w).RPosCompensate
                            Next

                            pointCAD(4) = photo_point(0)             '第一个拍照点X
                            pointCAD(5) = photo_point(1)                 '第一个拍照点Y
                            pointCAD(6) = photo_point(4)                 '第二个拍照点X
                            pointCAD(7) = photo_point(5)                 '第二个拍照点Y

                            If SendDataY(0) > Y轴_最大偏差限制 Or SendDataY(0) < Y轴_最小偏差限制 Then
                                AppendInfoToTextBox("第一个拍照点Y轴偏差超出限制")
                                SendDataY(0) = 99999
                            ElseIf SendDataY(2) > Y轴_最大偏差限制 Or SendDataY(2) < Y轴_最小偏差限制 Then
                                AppendInfoToTextBox("第二个拍照点Y轴偏差超出限制")
                                SendDataY(2) = 99999
                            End If

                            bzw = 0
                            ReturnXYR = TwoPointurn(SendDataX(0), SendDataY(0), SendDataX(2), SendDataY(2))

                            ReturnXYR.X1 += Pset(0).XPosCompensate + pointCAD(8)
                            ReturnXYR.Y1 += Pset(0).YPosCompensate + pointCAD(9)
                            ReturnXYR.X2 += Pset(1).XPosCompensate + pointCAD(10)
                            ReturnXYR.Y2 += Pset(1).YPosCompensate + pointCAD(11)
                            ReturnXYR.X3 += Pset(2).XPosCompensate + pointCAD(12)
                            ReturnXYR.Y3 += Pset(2).YPosCompensate + pointCAD(13)
                            ReturnXYR.X4 += Pset(3).XPosCompensate + pointCAD(14)
                            ReturnXYR.Y4 += Pset(3).YPosCompensate + pointCAD(15)
                            ReturnXYR.X5 += Pset(4).XPosCompensate + pointCAD(16)
                            ReturnXYR.Y5 += Pset(4).YPosCompensate + pointCAD(17)
                            ReturnXYR.X6 += Pset(5).XPosCompensate + pointCAD(18)
                            ReturnXYR.Y6 += Pset(5).YPosCompensate + pointCAD(19)
                            ReturnXYR.X7 += Pset(6).XPosCompensate + pointCAD(20)
                            ReturnXYR.Y7 += Pset(6).YPosCompensate + pointCAD(21)
                            ReturnXYR.X8 += Pset(7).XPosCompensate + pointCAD(22)
                            ReturnXYR.Y8 += Pset(7).YPosCompensate + pointCAD(23)
                            ReturnXYR.X9 += Pset(8).XPosCompensate + pointCAD(24)
                            ReturnXYR.Y9 += Pset(8).YPosCompensate + pointCAD(25)
                            ReturnXYR.X10 += Pset(9).XPosCompensate + pointCAD(26)
                            ReturnXYR.Y10 += Pset(9).YPosCompensate + pointCAD(27)
                            ReturnXYR.X11 += Pset(10).XPosCompensate + pointCAD(28)
                            ReturnXYR.Y11 += Pset(10).YPosCompensate + pointCAD(29)
                            ReturnXYR.X12 += Pset(11).XPosCompensate + pointCAD(30)
                            ReturnXYR.Y12 += Pset(11).YPosCompensate + pointCAD(31)
                            ReturnXYR.X13 += Pset(12).XPosCompensate + pointCAD(32)
                            ReturnXYR.Y13 += Pset(12).YPosCompensate + pointCAD(33)
                            ReturnXYR.X14 += Pset(13).XPosCompensate + pointCAD(34)
                            ReturnXYR.Y14 += Pset(13).YPosCompensate + pointCAD(35)
                            ReturnXYR.X15 += Pset(14).XPosCompensate + pointCAD(36)
                            ReturnXYR.Y15 += Pset(14).YPosCompensate + pointCAD(37)
                            ReturnXYR.X16 += Pset(15).XPosCompensate + pointCAD(38)
                            ReturnXYR.Y16 += Pset(15).YPosCompensate + pointCAD(39)
                            ReturnXYR.X17 += Pset(16).XPosCompensate + pointCAD(40)
                            ReturnXYR.Y17 += Pset(16).YPosCompensate + pointCAD(41)
                            ReturnXYR.X18 += Pset(17).XPosCompensate + pointCAD(42)
                            ReturnXYR.Y18 += Pset(17).YPosCompensate + pointCAD(43)
                            ReturnXYR.X19 += Pset(18).XPosCompensate + pointCAD(44)
                            ReturnXYR.Y19 += Pset(18).YPosCompensate + pointCAD(45)
                            ReturnXYR.X20 += Pset(19).XPosCompensate + pointCAD(46)
                            ReturnXYR.Y20 += Pset(19).YPosCompensate + pointCAD(47)
                            ReturnXYR.X21 += Pset(20).XPosCompensate + pointCAD(48)
                            ReturnXYR.Y21 += Pset(20).YPosCompensate + pointCAD(49)
                            ReturnXYR.X22 += Pset(21).XPosCompensate + pointCAD(50)
                            ReturnXYR.Y22 += Pset(21).YPosCompensate + pointCAD(51)
                            ReturnXYR.X23 += Pset(22).XPosCompensate + pointCAD(52)
                            ReturnXYR.Y23 += Pset(22).YPosCompensate + pointCAD(53)
                            ReturnXYR.X24 += Pset(23).XPosCompensate + pointCAD(54)
                            ReturnXYR.Y24 += Pset(23).YPosCompensate + pointCAD(55)
                            ReturnXYR.X25 += Pset(24).XPosCompensate + pointCAD(56)
                            ReturnXYR.Y25 += Pset(24).YPosCompensate + pointCAD(57)
                            ReturnXYR.X26 += Pset(25).XPosCompensate + pointCAD(58)
                            ReturnXYR.Y26 += Pset(25).YPosCompensate + pointCAD(59)
                            ReturnXYR.X27 += Pset(26).XPosCompensate + pointCAD(60)
                            ReturnXYR.Y27 += Pset(26).YPosCompensate + pointCAD(61)
                            ReturnXYR.X28 += Pset(27).XPosCompensate + pointCAD(62)
                            ReturnXYR.Y28 += Pset(27).YPosCompensate + pointCAD(63)
                            ReturnXYR.X29 += Pset(28).XPosCompensate + pointCAD(64)
                            ReturnXYR.Y29 += Pset(28).YPosCompensate + pointCAD(65)
                            ReturnXYR.X30 += Pset(29).XPosCompensate + pointCAD(66)
                            ReturnXYR.Y30 += Pset(29).YPosCompensate + pointCAD(67)

                            strSendData += vbCrLf

ss:
                            AppendInfoToTextBox("坐标:" & temp(5) & vbCrLf & "(" & Format(ReturnXYR.X1, "0.000") & "," & Format(ReturnXYR.Y1, "0.000") & "," & Format(pointCAD_Z(0), "0.000") & "," & Format(pointCAD_C(0), "0.000") & "," &
                                                                   Format(ReturnXYR.X2, "0.000") & "," & Format(ReturnXYR.Y2, "0.000") & "," & Format(pointCAD_Z(1), "0.000") & "," & Format(pointCAD_C(1), "0.000") & "," &
                                                                   Format(ReturnXYR.X3, "0.000") & "," & Format(ReturnXYR.Y3, "0.000") & "," & Format(pointCAD_Z(2), "0.000") & "," & Format(pointCAD_C(2), "0.000") & "," &
                                                                   Format(ReturnXYR.X4, "0.000") & "," & Format(ReturnXYR.Y4, "0.000") & "," & Format(pointCAD_Z(3), "0.000") & "," & Format(pointCAD_C(3), "0.000") & "," &
                                                                   Format(ReturnXYR.X5, "0.000") & "," & Format(ReturnXYR.Y5, "0.000") & "," & Format(pointCAD_Z(4), "0.000") & "," & Format(pointCAD_C(4), "0.000") & "," &
                                                                   Format(ReturnXYR.X6, "0.000") & "," & Format(ReturnXYR.Y6, "0.000") & "," & Format(pointCAD_Z(5), "0.000") & "," & Format(pointCAD_C(5), "0.000") & "," &
                                                                   Format(ReturnXYR.X7, "0.000") & "," & Format(ReturnXYR.Y7, "0.000") & "," & Format(pointCAD_Z(6), "0.000") & "," & Format(pointCAD_C(6), "0.000") & "," &
                                                                   Format(ReturnXYR.X8, "0.000") & "," & Format(ReturnXYR.Y8, "0.000") & "," & Format(pointCAD_Z(7), "0.000") & "," & Format(pointCAD_C(7), "0.000") & "," &
                                                                   Format(ReturnXYR.X9, "0.000") & "," & Format(ReturnXYR.Y9, "0.000") & "," & Format(pointCAD_Z(8), "0.000") & "," & Format(pointCAD_C(8), "0.000") & "," &
                                                                   Format(ReturnXYR.X10, "0.000") & "," & Format(ReturnXYR.Y10, "0.000") & "," & Format(pointCAD_Z(9), "0.000") & "," & Format(pointCAD_C(9), "0.000") & "," &
                                                                   Format(ReturnXYR.X11, "0.000") & "," & Format(ReturnXYR.Y11, "0.000") & "," & Format(pointCAD_Z(10), "0.000") & "," & Format(pointCAD_C(10), "0.000") & "," &
                                                                   Format(ReturnXYR.X12, "0.000") & "," & Format(ReturnXYR.Y12, "0.000") & "," & Format(pointCAD_Z(11), "0.000") & "," & Format(pointCAD_C(11), "0.000") & "," &
                                                                   Format(ReturnXYR.X13, "0.000") & "," & Format(ReturnXYR.Y13, "0.000") & "," & Format(pointCAD_Z(12), "0.000") & "," & Format(pointCAD_C(12), "0.000") & "," &
                                                                   Format(ReturnXYR.X14, "0.000") & "," & Format(ReturnXYR.Y14, "0.000") & "," & Format(pointCAD_Z(13), "0.000") & "," & Format(pointCAD_C(13), "0.000") & "," &
                                                                   Format(ReturnXYR.X15, "0.000") & "," & Format(ReturnXYR.Y15, "0.000") & "," & Format(pointCAD_Z(14), "0.000") & "," & Format(pointCAD_C(14), "0.000") & "," &
                                                                   Format(ReturnXYR.X16, "0.000") & "," & Format(ReturnXYR.Y16, "0.000") & "," & Format(pointCAD_Z(15), "0.000") & "," & Format(pointCAD_C(15), "0.000") & "," &
                                                                   Format(ReturnXYR.X17, "0.000") & "," & Format(ReturnXYR.Y17, "0.000") & "," & Format(pointCAD_Z(16), "0.000") & "," & Format(pointCAD_C(16), "0.000") & "," &
                                                                   Format(ReturnXYR.X18, "0.000") & "," & Format(ReturnXYR.Y18, "0.000") & "," & Format(pointCAD_Z(17), "0.000") & "," & Format(pointCAD_C(17), "0.000") & "," &
                                                                   Format(ReturnXYR.X19, "0.000") & "," & Format(ReturnXYR.Y19, "0.000") & "," & Format(pointCAD_Z(18), "0.000") & "," & Format(pointCAD_C(18), "0.000") & "," &
                                                                   Format(ReturnXYR.X20, "0.000") & "," & Format(ReturnXYR.Y20, "0.000") & "," & Format(pointCAD_Z(19), "0.000") & "," & Format(pointCAD_C(19), "0.000") & "," &
                                                                   Format(ReturnXYR.X21, "0.000") & "," & Format(ReturnXYR.Y21, "0.000") & "," & Format(pointCAD_Z(20), "0.000") & "," & Format(pointCAD_C(20), "0.000") & "," &
                                                                   Format(ReturnXYR.X22, "0.000") & "," & Format(ReturnXYR.Y22, "0.000") & "," & Format(pointCAD_Z(21), "0.000") & "," & Format(pointCAD_C(21), "0.000") & "," &
                                                                   Format(ReturnXYR.X23, "0.000") & "," & Format(ReturnXYR.Y23, "0.000") & "," & Format(pointCAD_Z(22), "0.000") & "," & Format(pointCAD_C(22), "0.000") & "," &
                                                                   Format(ReturnXYR.X24, "0.000") & "," & Format(ReturnXYR.Y24, "0.000") & "," & Format(pointCAD_Z(23), "0.000") & "," & Format(pointCAD_C(23), "0.000") & "," &
                                                                   Format(ReturnXYR.X25, "0.000") & "," & Format(ReturnXYR.Y25, "0.000") & "," & Format(pointCAD_Z(24), "0.000") & "," & Format(pointCAD_C(24), "0.000") & "," &
                                                                   Format(ReturnXYR.X26, "0.000") & "," & Format(ReturnXYR.Y26, "0.000") & "," & Format(pointCAD_Z(25), "0.000") & "," & Format(pointCAD_C(25), "0.000") & "," &
                                                                   Format(ReturnXYR.X27, "0.000") & "," & Format(ReturnXYR.Y27, "0.000") & "," & Format(pointCAD_Z(26), "0.000") & "," & Format(pointCAD_C(26), "0.000") & "," &
                                                                   Format(ReturnXYR.X28, "0.000") & "," & Format(ReturnXYR.Y28, "0.000") & "," & Format(pointCAD_Z(27), "0.000") & "," & Format(pointCAD_C(27), "0.000") & "," &
                                                                   Format(ReturnXYR.X29, "0.000") & "," & Format(ReturnXYR.Y29, "0.000") & "," & Format(pointCAD_Z(28), "0.000") & "," & Format(pointCAD_C(28), "0.000") & "," &
                                                                   Format(ReturnXYR.X30, "0.000") & "," & Format(ReturnXYR.Y30, "0.000") & "," & Format(pointCAD_Z(29), "0.000") & "," & Format(pointCAD_C(29), "0.000") & "," & vbCrLf)

                            Dim byteSend1 As Byte() = Encoding.ASCII.GetBytes(Format(ReturnXYR.X1, "0.000") & "," & Format(ReturnXYR.Y1, "0.000") & "," & Format(pointCAD_Z(0), "0.000") & "," & Format(pointCAD_C(0), "0.000") & "," &
                                                                      Format(ReturnXYR.X2, "0.000") & "," & Format(ReturnXYR.Y2, "0.00") & "," & Format(pointCAD_Z(1), "0.00") & "," & Format(pointCAD_C(1), "0.000") & "," &
                                                                      Format(ReturnXYR.X3, "0.000") & "," & Format(ReturnXYR.Y3, "0.000") & "," & Format(pointCAD_Z(2), "0.000") & "," & Format(pointCAD_C(2), "0.000") & "," &
                                                                      Format(ReturnXYR.X4, "0.000") & "," & Format(ReturnXYR.Y4, "0.000") & "," & Format(pointCAD_Z(3), "0.000") & "," & Format(pointCAD_C(3), "0.000") & "," &
                                                                      Format(ReturnXYR.X5, "0.000") & "," & Format(ReturnXYR.Y5, "0.000") & "," & Format(pointCAD_Z(4), "0.000") & "," & Format(pointCAD_C(4), "0.000") & "," &
                                                                      Format(ReturnXYR.X6, "0.000") & "," & Format(ReturnXYR.Y6, "0.000") & "," & Format(pointCAD_Z(5), "0.000") & "," & Format(pointCAD_C(5), "0.000") & "," &
                                                                      Format(ReturnXYR.X7, "0.000") & "," & Format(ReturnXYR.Y7, "0.000") & "," & Format(pointCAD_Z(6), "0.000") & "," & Format(pointCAD_C(6), "0.000") & "," &
                                                                      Format(ReturnXYR.X8, "0.000") & "," & Format(ReturnXYR.Y8, "0.000") & "," & Format(pointCAD_Z(7), "0.000") & "," & Format(pointCAD_C(7), "0.000") & "," & vbCrLf)

                            Dim byteSend2 As Byte() = Encoding.ASCII.GetBytes(Format(ReturnXYR.X9, "0.000") & "," & Format(ReturnXYR.Y9, "0.000") & "," & Format(pointCAD_Z(8), "0.000") & "," & Format(pointCAD_C(8), "0.000") & "," &
                                                                      Format(ReturnXYR.X10, "0.000") & "," & Format(ReturnXYR.Y10, "0.000") & "," & Format(pointCAD_Z(9), "0.000") & "," & Format(pointCAD_C(9), "0.000") & "," &
                                                                      Format(ReturnXYR.X11, "0.000") & "," & Format(ReturnXYR.Y11, "0.000") & "," & Format(pointCAD_Z(10), "0.000") & "," & Format(pointCAD_C(10), "0.000") & "," &
                                                                      Format(ReturnXYR.X12, "0.000") & "," & Format(ReturnXYR.Y12, "0.000") & "," & Format(pointCAD_Z(11), "0.000") & "," & Format(pointCAD_C(11), "0.000") & "," &
                                                                      Format(ReturnXYR.X13, "0.000") & "," & Format(ReturnXYR.Y13, "0.000") & "," & Format(pointCAD_Z(12), "0.000") & "," & Format(pointCAD_C(12), "0.000") & "," &
                                                                      Format(ReturnXYR.X14, "0.000") & "," & Format(ReturnXYR.Y14, "0.000") & "," & Format(pointCAD_Z(13), "0.000") & "," & Format(pointCAD_C(13), "0.000") & "," &
                                                                      Format(ReturnXYR.X15, "0.000") & "," & Format(ReturnXYR.Y15, "0.000") & "," & Format(pointCAD_Z(14), "0.000") & "," & Format(pointCAD_C(14), "0.000") & "," & vbCrLf)

                            Dim byteSend3 As Byte() = Encoding.ASCII.GetBytes(Format(ReturnXYR.X16, "0.000") & "," & Format(ReturnXYR.Y16, "0.000") & "," & Format(pointCAD_Z(15), "0.000") & "," & Format(pointCAD_C(15), "0.000") & "," &
                                                                      Format(ReturnXYR.X17, "0.000") & "," & Format(ReturnXYR.Y17, "0.000") & "," & Format(pointCAD_Z(16), "0.000") & "," & Format(pointCAD_C(16), "0.000") & "," &
                                                                      Format(ReturnXYR.X18, "0.000") & "," & Format(ReturnXYR.Y18, "0.000") & "," & Format(pointCAD_Z(17), "0.000") & "," & Format(pointCAD_C(17), "0.000") & "," &
                                                                      Format(ReturnXYR.X19, "0.000") & "," & Format(ReturnXYR.Y19, "0.000") & "," & Format(pointCAD_Z(18), "0.000") & "," & Format(pointCAD_C(18), "0.000") & "," &
                                                                      Format(ReturnXYR.X20, "0.000") & "," & Format(ReturnXYR.Y20, "0.000") & "," & Format(pointCAD_Z(19), "0.000") & "," & Format(pointCAD_C(19), "0.000") & "," &
                                                                      Format(ReturnXYR.X21, "0.000") & "," & Format(ReturnXYR.Y21, "0.000") & "," & Format(pointCAD_Z(20), "0.000") & "," & Format(pointCAD_C(20), "0.000") & "," &
                                                                      Format(ReturnXYR.X22, "0.000") & "," & Format(ReturnXYR.Y22, "0.000") & "," & Format(pointCAD_Z(21), "0.000") & "," & Format(pointCAD_C(21), "0.000") & "," &
                                                                      Format(ReturnXYR.X23, "0.000") & "," & Format(ReturnXYR.Y23, "0.000") & "," & Format(pointCAD_Z(22), "0.000") & "," & Format(pointCAD_C(22), "0.000") & "," & vbCrLf)
                            Dim byteSend4 As Byte() = Encoding.ASCII.GetBytes(Format(ReturnXYR.X24, "0.000") & "," & Format(ReturnXYR.Y24, "0.000") & "," & Format(pointCAD_Z(23), "0.000") & "," & Format(pointCAD_C(23), "0.000") & "," &
                                                                     Format(ReturnXYR.X25, "0.000") & "," & Format(ReturnXYR.Y25, "0.000") & "," & Format(pointCAD_Z(24), "0.000") & "," & Format(pointCAD_C(24), "0.000") & "," &
                                                                     Format(ReturnXYR.X26, "0.000") & "," & Format(ReturnXYR.Y26, "0.000") & "," & Format(pointCAD_Z(25), "0.000") & "," & Format(pointCAD_C(25), "0.000") & "," &
                                                                     Format(ReturnXYR.X27, "0.000") & "," & Format(ReturnXYR.Y27, "0.000") & "," & Format(pointCAD_Z(26), "0.000") & "," & Format(pointCAD_C(26), "0.000") & "," &
                                                                     Format(ReturnXYR.X28, "0.000") & "," & Format(ReturnXYR.Y28, "0.000") & "," & Format(pointCAD_Z(27), "0.000") & "," & Format(pointCAD_C(27), "0.000") & "," &
                                                                     Format(ReturnXYR.X29, "0.000") & "," & Format(ReturnXYR.Y29, "0.000") & "," & Format(pointCAD_Z(28), "0.000") & "," & Format(pointCAD_C(28), "0.000") & "," &
                                                                     Format(ReturnXYR.X30, "0.000") & "," & Format(ReturnXYR.Y30, "0.000") & "," & Format(pointCAD_Z(29), "0.000") & "," & Format(pointCAD_C(29), "0.000") & "," & vbCrLf)

                            SNPoint_X = Format(ReturnXYR.X1, "0.000") & "," & Format(ReturnXYR.X2, "0.000") & "," & Format(ReturnXYR.X3, "0.000") & "," & Format(ReturnXYR.X4, "0.000") & "," & Format(ReturnXYR.X5, "0.000") & "," & Format(ReturnXYR.X6, "0.000") & "," & Format(ReturnXYR.X7, "0.000") & "," & Format(ReturnXYR.X8, "0.000") & "," & Format(ReturnXYR.X9, "0.000") & "," & Format(ReturnXYR.X10, "0.000") & "," & Format(ReturnXYR.X11, "0.000") & "," & Format(ReturnXYR.X12, "0.000") & "," & Format(ReturnXYR.X13, "0.000") & "," & Format(ReturnXYR.X14, "0.000") & "," & Format(ReturnXYR.X15, "0.000")
                            SNPoint_Y = Format(ReturnXYR.Y1, "0.000") & "," & Format(ReturnXYR.Y2, "0.000") & "," & Format(ReturnXYR.Y3, "0.000") & "," & Format(ReturnXYR.Y4, "0.000") & "," & Format(ReturnXYR.Y5, "0.000") & "," & Format(ReturnXYR.Y6, "0.000") & "," & Format(ReturnXYR.Y7, "0.000") & "," & Format(ReturnXYR.Y8, "0.000") & "," & Format(ReturnXYR.Y9, "0.000") & "," & Format(ReturnXYR.Y10, "0.000") & "," & Format(ReturnXYR.Y11, "0.000") & "," & Format(ReturnXYR.Y12, "0.000") & "," & Format(ReturnXYR.Y13, "0.000") & "," & Format(ReturnXYR.Y14, "0.000") & "," & Format(ReturnXYR.Y15, "0.000")
                            SNPoint_Z = Format(pointCAD_Z(0), "0.000") & "," & Format(pointCAD_Z(1), "0.000") & "," & Format(pointCAD_Z(2), "0.000") & "," & Format(pointCAD_Z(3), "0.000") & "," & Format(pointCAD_Z(4), "0.000") & "," & Format(pointCAD_Z(5), "0.000") & "," & Format(pointCAD_Z(6), "0.000") & "," & Format(pointCAD_Z(7), "0.000") & "," & Format(pointCAD_Z(8), "0.000") & "," & Format(pointCAD_Z(9), "0.000") & "," & Format(pointCAD_Z(10), "0.000") & "," & Format(pointCAD_Z(11), "0.000") & "," & Format(pointCAD_Z(12), "0.000") & "," & Format(pointCAD_Z(13), "0.000") & "," & Format(pointCAD_Z(14), "0.000")
                            MySocket.Send(byteSend1)
                            waitstandby(50)
                            MySocket.Send(byteSend2)
                            If CurScrewPara.PointCount > 15 Then
                                waitstandby(50)
                                MySocket.Send(byteSend3)
                                waitstandby(50)
                                MySocket.Send(byteSend4)
                            End If

                            If ReturnXYR.X1 < 700 Then
                                Todaycount.PassCount += 1
                                TextBox1.Text = Todaycount.PassCount.ToString
                            End If
                            TSRest.Text = (DateTime.Now.Ticks - __time.Ticks) / 10000 & "ms"

                            CogRecordDisplay4.Image = CogIPOneImageTool1.OutputImage
                            CogRecordDisplay4.Fit()
                            If tmpfifo0.Operator.FrameGrabber IsNot Nothing Then
                                CogRecordDisplay4.Record = tmpPmalign.CreateLastRunRecord
                            End If
                        Else
                            SecondCCDState = 3
                        End If

                    End If
                Else
                    SecondCCDState = 1
                End If
            Else
                SecondCCDState = 2
                GoTo c
                AppendInfoToTextBox("未连接摄像机！")
            End If
        Catch ex As Exception
            AppendInfoToTextBox(ex.StackTrace.ToString)
            WriteInspecLog(TSLog, "SecondCameraImageProcess" & vbTab & ex.StackTrace.ToString)
            MsgBox(ex.StackTrace.ToString)
        End Try

d:
    End Sub

    ''' <summary>
    ''' 英业达扫码使用
    ''' </summary>
    ''' <param name="MySocket"></param>
    ''' <param name="StrReceData"></param>
    ''' <remarks></remarks>
    Private Sub CCD_cameraimagescancode(ByRef MySocket As Socket, ByVal StrReceData As String)
        Dim __time As DateTime = DateTime.Now
        AppendInfoToTextBox("ThirdCameraImageProcess")
        Try
            Dim tmpfifo0 As CogAcqFifoTool = gTBCheck(2).Tools.Item("相机设定")
            Dim tmpBarcode As CogBarcodeTool = gTBCheck(2).Tools.Item("CogBarcodeTool1")
            Dim strErrorInfo As String = ""
            Dim strSendData As String = ""
            Dim SDFSFS As String = ""
            Dim bHasObject As Boolean = False
            If tmpfifo0.Operator.FrameGrabber IsNot Nothing Then
                AppendInfoToTextBox("FrameGrabber")
                If True Then
                    tmpfifo0.Run()
                    If tmpfifo0.OutputImage Is Nothing Then
                        AppendInfoToTextBox(tmpfifo0.RunStatus.Exception.ToString)
                        AppendInfoToTextBox(tmpfifo0.RunStatus.Message)
                        tmpfifo0.Run()
                        AppendInfoToTextBox("AcqBaseImage首次取相失败，再进行第二次取相")
                        If tmpfifo0.OutputImage Is Nothing Then
                            SecondCCDState = 2
                            GoTo c
                        Else
                            GoTo sucess
                        End If
                    Else
sucess:
                        If tmpfifo0.OutputImage IsNot Nothing Then
                            SecondCCDState = 0 '正常
                            AppendInfoToTextBox("tmpBarcode.Run()")
                            tmpBarcode.Run()

                            If tmpBarcode.RunStatus.Result = CogToolResultConstants.Accept Then
                                If tmpBarcode.Results.Count > 0 Then
                                    Dim barcode As String = tmpBarcode.Results.Item(0).OwnedDecoded.String              '扫码数据
                                    Dim Breakbarcode() As String = barcode.Split("-")                                  '条形码拆分
                                    AppendInfoToTextBox("条码：" & barcode)

                                    If Breakbarcode.Length >= 2 Then
                                        Dim model As String = 扫码模板管理.query(Breakbarcode(0))         '根据条形码数值进行查询代码
                                        If model <> "" Then
                                            AppendInfoToTextBox("查询条码：" & model)
                                            strSendData = model
                                        Else
                                            strSendData = "2"   '未扫到条码
                                            AppendInfoToTextBox("未找到匹配模板")
                                        End If
                                    Else
                                        strSendData = "2"   '未扫到条码
                                        AppendInfoToTextBox("条码类型错误")
                                    End If
                                Else
                                    strSendData = "2"   '未扫到条码
                                    AppendInfoToTextBox("未扫到条码")
                                End If
c:
                                If SecondCCDState = 2 Then
                                    strSendData = "2"
                                End If
                            Else
                                strSendData = "2"
                            End If

                            If strSendData = "2" Then
                                'Dim barcode As String = "X64A-Red"
                                'Dim Breakbarcode() As String = barcode.Split("-")
                                'strSendData = 扫码模板管理.query(Breakbarcode(0), Breakbarcode(1))
                                'strSendData = 扫码模板管理.query("X64A", "Red")         '根据条形码数值进行查询代码
                                strSendData = Chanpin
                                SDFSFS = 2
                            Else
                                SDFSFS = 1
                            End If
                            TCmbPro.Text = strSendData
                            AppendInfoToTextBox("4:" & vbCrLf & strSendData + vbCrLf)
                            Dim byteSend As Byte() = Encoding.ASCII.GetBytes(strSendData & "," & SDFSFS & vbCrLf)
                            MySocket.Send(byteSend)

                            TSRest.Text = (DateTime.Now.Ticks - __time.Ticks) / 10000 & "ms"

                            CogRecordDisplay1.Image = tmpfifo0.OutputImage
                            CogRecordDisplay1.Fit()
                            If tmpfifo0.Operator.FrameGrabber IsNot Nothing Then
                                CogRecordDisplay1.Record = tmpBarcode.CreateLastRunRecord
                            End If
                        Else
                            SecondCCDState = 2
                        End If
                    End If
                Else
                    SecondCCDState = 2
                End If
            Else
                SecondCCDState = 2
                GoTo c
                AppendInfoToTextBox("未连接摄像机！")
            End If
        Catch ex As Exception
            WriteInspecLog(TSLog, "SecondCameraImageProcess" & vbTab & ex.StackTrace.ToString)
            MsgBox(ex.StackTrace.ToString)
        End Try

d:
    End Sub

    ''' <summary>
    ''' 英业达扫特征点
    ''' </summary>
    ''' <param name="MySocket"></param>
    ''' <param name="StrReceData"></param>
    ''' <remarks></remarks>
    Private Sub ThirdCameraImageProcess(ByRef MySocket As Socket, ByVal StrReceData As String)
        Dim __time As DateTime = DateTime.Now
        AppendInfoToTextBox("ThirdCameraImageProcess")
        Try
            Dim tmpfifo0 As CogAcqFifoTool = gTBCheck(2).Tools.Item("相机设定")
            Dim tmpCalibCB As CogCalibCheckerboardTool = gTBCheck(2).Tools.Item("CogCalibCheckerboardTool1")
            Dim tmpCogCalibCheckerboardTool As CogCalibNPointToNPointTool = gTBCheck(2).Tools.Item("CogCalibNPointToNPointTool1")
            Dim tmpPmalign1 As CogPMAlignTool = gTBCheck(2).Tools.Item("CogPMAlignTool1")
            Dim CogIPOneImageTool1 As CogIPOneImageTool = gTBCheck(2).Tools.Item("CogIPOneImageTool1")
            Dim tmpPmalign As CogPMAlignTool = tmpPmalign1
            Dim strErrorInfo As String = ""
            Dim strSendData As String = ""
            Dim bHasObject As Boolean = False
            If tmpfifo0.Operator.FrameGrabber IsNot Nothing Then
                AppendInfoToTextBox("FrameGrabber")
                If True Then
                    tmpfifo0.Run()
                    If tmpfifo0.OutputImage Is Nothing Then
                        AppendInfoToTextBox(tmpfifo0.RunStatus.Exception.ToString)
                        AppendInfoToTextBox(tmpfifo0.RunStatus.Message)
                        tmpfifo0.Run()
                        AppendInfoToTextBox("AcqBaseImage首次取相失败，再进行第二次取相")
                        If tmpfifo0.OutputImage Is Nothing Then
                            SecondCCDState = 2
                            GoTo c
                        Else
                            GoTo sucess
                        End If
                    Else
sucess:
                        If tmpfifo0.OutputImage IsNot Nothing Then
                            SecondCCDState = 0 '正常
                            AppendInfoToTextBox("tmpCalibCB.Run()")
                            CogIPOneImageTool1.Run()
                            tmpCalibCB.Run()
                            tmpCogCalibCheckerboardTool.Run()
                            tmpPmalign1.Run()
                            Dim dTemp As Double = 0
                            Dim dTemp2 As String = ""
                            If tmpPmalign1.RunStatus.Result = CogToolResultConstants.Accept Then
                                If tmpPmalign.Results.Count > 0 Then
                                    strSendData = KESU.ToString   '抓到mark
                                    AppendInfoToTextBox("抓到第三拍照点特征mark,锁付颗数改变为：" + KESU.ToString)
                                Else
                                    strSendData = CurScrewPara.PointCount.ToString   '未抓到mark
                                    AppendInfoToTextBox("未抓到第三拍照点特征mark，锁付颗数不变：" + CurScrewPara.PointCount.ToString)
                                End If
                                If tmpPmalign.Results.Count < 1 Then
                                    'Dim fileName As String = gVisionFailedPath & TCmbPro.Text & "\" & Format(Date.Now.Date, "yyyyMMdd") & Format(DateTime.Now.Ticks) & ".jpg"
                                    'Dim filePath As String = gVisionFailedPath & TCmbPro.Text & "\"
                                    'YSPic(CogRecordDisplay1, tmpfifo0, filePath, fileName)
                                    AppendInfoToTextBox("未抓到mark")
                                    strSendData = CurScrewPara.PointCount.ToString
                                End If
c:
                                If SecondCCDState = 2 Then
                                    strSendData = CurScrewPara.PointCount.ToString
                                End If
                            Else
                                strSendData = CurScrewPara.PointCount.ToString
                            End If
                            AppendInfoToTextBox("3:" & vbCrLf & strSendData + vbCrLf)

                            Dim byteSend As Byte() = Encoding.ASCII.GetBytes(strSendData & vbCrLf)
                            MySocket.Send(byteSend)

                            TSRest.Text = (DateTime.Now.Ticks - __time.Ticks) / 10000 & "ms"

                            CogRecordDisplay1.Image = CogIPOneImageTool1.OutputImage
                            CogRecordDisplay1.Fit()
                            If tmpfifo0.Operator.FrameGrabber IsNot Nothing Then
                                CogRecordDisplay1.Record = tmpPmalign.CreateLastRunRecord
                            End If
                        Else
                            SecondCCDState = 3
                        End If

                    End If
                Else
                    SecondCCDState = 1
                End If
            Else
                SecondCCDState = 2
                GoTo c
                AppendInfoToTextBox("未连接摄像机！")
            End If
        Catch ex As Exception
            WriteInspecLog(TSLog, "SecondCameraImageProcess" & vbTab & ex.StackTrace.ToString)
            MsgBox(ex.StackTrace.ToString)
        End Try

d:
    End Sub

    Private Sub auto1(ByRef MySocket As Socket, ByVal StrReceData As String)
        Dim __time As DateTime = DateTime.Now
        AppendInfoToTextBox("auto1 run")
        Try
            Dim tmpfifo0 As CogAcqFifoTool = gTBCheck(0).Tools.Item("相机设定")
            Dim tmpCalibCB As CogCalibCheckerboardTool = gTBCheck(0).Tools.Item("CogCalibCheckerboardTool1")
            Dim tmpCogCalibCheckerboardTool As CogCalibNPointToNPointTool = gTBCheck(0).Tools.Item("CogCalibNPointToNPointTool1")
            Dim tmpPmalign1 As CogPMAlignTool = gTBCheck(0).Tools.Item("CogPMAlignTool1")
            Dim CogIPOneImageTool1 As CogIPOneImageTool = gTBCheck(0).Tools.Item("CogIPOneImageTool1")

            Dim tmpPmalign As CogPMAlignTool = tmpPmalign1
            Dim strErrorInfo As String = ""
            Dim strSendData As String = ""
            Dim bHasObject As Boolean = False
            If tmpfifo0.Operator.FrameGrabber IsNot Nothing Then
                AppendInfoToTextBox("FrameGrabber")
                If True Then

                    tmpfifo0.Run()
                    If tmpfifo0.OutputImage Is Nothing Then
                        AppendInfoToTextBox(tmpfifo0.RunStatus.Exception.ToString)
                        AppendInfoToTextBox(tmpfifo0.RunStatus.Message)
                        tmpfifo0.Run()
                        AppendInfoToTextBox("AcqBaseImage首次取相失败，再进行第二次取相")
                        If tmpfifo0.OutputImage Is Nothing Then
                            SecondCCDState = 2
                            GoTo c
                        Else
                            GoTo sucess
                        End If
                    Else
sucess:
                        If tmpfifo0.OutputImage IsNot Nothing Then
                            SecondCCDState = 0 '正常
                            AppendInfoToTextBox("tmpCalibCB.Run()")
                            CogIPOneImageTool1.Run()
                            tmpCalibCB.Run()
                            tmpCogCalibCheckerboardTool.Run()
                            tmpPmalign1.Run()
                            Dim dTemp As Double = 0
                            Dim dTemp2 As String = ""
                            If tmpPmalign1.RunStatus.Result = CogToolResultConstants.Accept Then

                                If tmpPmalign.Results.Count > 0 Then
                                    dTemp = tmpPmalign.Results.Item(0).GetPose.TranslationX.ToString
                                    dTemp2 = Format(dTemp, "000.00")
                                    SendDataX(0) = dTemp
                                    strSendData += dTemp2 & ","
                                    dTemp = tmpPmalign.Results.Item(0).GetPose.TranslationY.ToString
                                    dTemp2 = Format(dTemp, "000.00")
                                    SendDataY(0) = dTemp
                                    strSendData += dTemp2 & ","
                                    dTemp = 0
                                    dTemp += tmpPmalign.Results.Item(0).GetPose.Rotation / Acos(-1) * 180
                                    dTemp2 = Format(dTemp, "000.00")
                                    SendDataR(0) = dTemp
                                    AppendInfoToTextBox(" SendDataR(0) = dTemp")
                                    strSendData += dTemp2 & ","
                                Else
                                    strSendData += "999" + ","
                                    strSendData += "999" + ","
                                    strSendData += "229.9,"
                                    strSendData += "0"
                                    SendDataX(0) = 999999.0
                                End If
                                If tmpPmalign.Results.Count < 1 Then
                                    Dim fileName As String = Format(Date.Now.Date, "yyyyMMdd") & Format(DateTime.Now.Ticks) & ".jpg"
                                    Dim filePath As String = gVisionFailedPath & Chanpin & "\" & Format(Date.Now.Date, "yyyyMMdd") & "\" & Chanpin & "\" & "Fail Image\"
                                    YSPic(CogRecordDisplay2, CogIPOneImageTool1, filePath, fileName)
                                End If
c:
                                If SecondCCDState = 2 Then
                                    strSendData += "999,999,0,0"
                                    SendDataX(0) = 999999.0
                                End If
                            Else
                                strSendData += "999,0,0,0"
                                SendDataX(0) = 999999.0
                            End If
                            strSendData += "" ' vbCrLf
                            AppendInfoToTextBox("2:" & vbCrLf & strSendData + vbCrLf)
                            Dim byteSend As Byte() = Encoding.ASCII.GetBytes(SendDataX(0) & "," & SendDataY(0) & "," & SendDataR(0) & vbCrLf)
                            MySocket.Send(byteSend)
                            TSRest.Text = (DateTime.Now.Ticks - __time.Ticks) / 10000 & "ms"

                            CogRecordDisplay2.Image = CogIPOneImageTool1.OutputImage
                            CogRecordDisplay2.Fit()
                            If tmpfifo0.Operator.FrameGrabber IsNot Nothing Then
                                CogRecordDisplay2.Record = tmpPmalign.CreateLastRunRecord
                            End If
                        Else
                            SecondCCDState = 3
                        End If

                    End If
                Else
                    SecondCCDState = 1
                End If
            Else
                SecondCCDState = 2
                GoTo c
                AppendInfoToTextBox("未连接摄像机！")
            End If
        Catch ex As Exception
            WriteInspecLog(TSLog, "auto1" & vbTab & ex.StackTrace.ToString)
            MsgBox(ex.StackTrace.ToString)
        End Try

        'CadToRobot()

d:
    End Sub

    Private Sub auto2(ByRef MySocket As Socket, ByVal StrReceData As String)
        Dim __time As DateTime = DateTime.Now
        AppendInfoToTextBox("auto2 run")
        Try
            Dim tmpfifo0 As CogAcqFifoTool = gTBCheck(1).Tools.Item("相机设定")
            Dim tmpCalibCB As CogCalibCheckerboardTool = gTBCheck(1).Tools.Item("CogCalibCheckerboardTool1")
            Dim tmpCogCalibCheckerboardTool As CogCalibNPointToNPointTool = gTBCheck(1).Tools.Item("CogCalibNPointToNPointTool1")
            Dim tmpPmalign1 As CogPMAlignTool = gTBCheck(1).Tools.Item("CogPMAlignTool1")
            Dim CogIPOneImageTool1 As CogIPOneImageTool = gTBCheck(1).Tools.Item("CogIPOneImageTool1")
            Dim tmpPmalign As CogPMAlignTool = tmpPmalign1
            Dim strErrorInfo As String = ""
            Dim strSendData As String = ""
            Dim bHasObject As Boolean = False
            If tmpfifo0.Operator.FrameGrabber IsNot Nothing Then
                AppendInfoToTextBox("FrameGrabber")
                If True Then
                    'If tmpfifo0.Operator.FrameGrabber.SerialNumber = SecondCCDSerNum Then
                    tmpfifo0.Run()
                    If tmpfifo0.OutputImage Is Nothing Then
                        AppendInfoToTextBox(tmpfifo0.RunStatus.Exception.ToString)
                        AppendInfoToTextBox(tmpfifo0.RunStatus.Message)
                        tmpfifo0.Run()
                        AppendInfoToTextBox("AcqBaseImage首次取相失败，再进行第二次取相")
                        If tmpfifo0.OutputImage Is Nothing Then
                            SecondCCDState = 2
                            GoTo c
                        Else
                            GoTo sucess
                        End If
                    Else
sucess:
                        If tmpfifo0.OutputImage IsNot Nothing Then
                            AppendInfoToTextBox("ForthCameraImageProcess tmpCalibCB.Run()")
                            SecondCCDState = 0 '正常
                            CogIPOneImageTool1.Run()
                            tmpCalibCB.Run()
                            tmpCogCalibCheckerboardTool.Run()
                            tmpPmalign1.Run()
                            Dim dTemp As Double = 0
                            Dim dTemp2 As String = ""

                            If tmpPmalign1.RunStatus.Result = CogToolResultConstants.Accept Then
                                If tmpPmalign.Results.Count > 0 Then
                                    dTemp = tmpPmalign.Results.Item(0).GetPose.TranslationX.ToString
                                    dTemp2 = Format(dTemp, "000.00")
                                    SendDataX(2) = dTemp
                                    strSendData += dTemp2 & ","
                                    dTemp = tmpPmalign.Results.Item(0).GetPose.TranslationY.ToString
                                    dTemp2 = Format(dTemp, "000.00")
                                    SendDataY(2) = dTemp
                                    strSendData += dTemp2 & ","
                                    dTemp = 0
                                    dTemp += tmpPmalign.Results.Item(0).GetPose.Rotation / Acos(-1) * 180
                                    dTemp2 = Format(dTemp, "000.00")
                                    SendDataR(2) = dTemp
                                    AppendInfoToTextBox("SendDataR(2) = dTemp")
                                    strSendData += dTemp2 & ","
                                Else
                                    SendDataX(2) = 999999
                                End If
                                If tmpPmalign.Results.Count < 1 Then
                                    Dim fileName As String = Format(Date.Now.Date, "yyyyMMdd") & Format(DateTime.Now.Ticks) & ".jpg"
                                    Dim filePath As String = gVisionFailedPath & Chanpin & "\" & Format(Date.Now.Date, "yyyyMMdd") & "\" & Chanpin & "\" & "Fail Image\"
                                    YSPic(CogRecordDisplay2, CogIPOneImageTool1, filePath, fileName)
                                End If

c:
                                If SecondCCDState = 2 Then
                                    strSendData += "999,999,0,0"
                                    SendDataX(2) = 999999.0
                                End If
                            Else
                                strSendData += "999,0,0,0"
                                SendDataX(2) = 999999.0
                            End If

                            AppendInfoToTextBox("2:" & vbCrLf & strSendData + vbCrLf)
                            Dim byteSend As Byte() = Encoding.ASCII.GetBytes(SendDataX(2) & "," & SendDataY(2) & "," & SendDataR(2) & vbCrLf)
                            MySocket.Send(byteSend)

                            TSRest.Text = (DateTime.Now.Ticks - __time.Ticks) / 10000 & "ms"

                            CogRecordDisplay4.Image = CogIPOneImageTool1.OutputImage
                            CogRecordDisplay4.Fit()
                            If tmpfifo0.Operator.FrameGrabber IsNot Nothing Then
                                CogRecordDisplay4.Record = tmpPmalign.CreateLastRunRecord
                            End If
                        Else
                            SecondCCDState = 3
                        End If

                    End If
                Else
                    SecondCCDState = 1
                End If
            Else
                SecondCCDState = 2
                GoTo c
                AppendInfoToTextBox("未连接摄像机！")
            End If
        Catch ex As Exception
            AppendInfoToTextBox(ex.StackTrace.ToString)
            WriteInspecLog(TSLog, "auto2" & vbTab & ex.StackTrace.ToString)
            MsgBox(ex.StackTrace.ToString)
        End Try

d:
    End Sub

    Private Sub SinglePointCameraProcess_1(ByRef MySocket As Socket, ByVal StrReceData As String)
        Dim __time As DateTime = DateTime.Now
        AppendInfoToTextBox("SinglePointCameraProcess_1 run")
        Try
            Dim tmpfifo0 As CogAcqFifoTool = gTBCheck(2).Tools.Item("相机设定")
            Dim tmpCalibCB As CogCalibCheckerboardTool = gTBCheck(2).Tools.Item("CogCalibCheckerboardTool1")
            Dim tmpCogCalibCheckerboardTool As CogCalibNPointToNPointTool = gTBCheck(2).Tools.Item("CogCalibNPointToNPointTool1")
            Dim tmpPmalign1 As CogPMAlignTool = gTBCheck(2).Tools.Item("CogPMAlignTool1")
            Dim CogIPOneImageTool1 As CogIPOneImageTool = gTBCheck(2).Tools.Item("CogIPOneImageTool1")
            Dim tmpPmalign As CogPMAlignTool = tmpPmalign1
            Dim strErrorInfo As String = ""
            Dim strSendData As String = ""
            Dim bHasObject As Boolean = False
            If tmpfifo0.Operator.FrameGrabber IsNot Nothing Then
                AppendInfoToTextBox("FrameGrabber")
                If True Then
                    tmpfifo0.Run()
                    If tmpfifo0.OutputImage Is Nothing Then
                        AppendInfoToTextBox(tmpfifo0.RunStatus.Exception.ToString)
                        AppendInfoToTextBox(tmpfifo0.RunStatus.Message)
                        tmpfifo0.Run()
                        AppendInfoToTextBox("AcqBaseImage首次取相失败，再进行第二次取相")
                        If tmpfifo0.OutputImage Is Nothing Then
                            SecondCCDState = 2
                            GoTo c
                        Else
                            GoTo sucess
                        End If
                    Else
sucess:
                        If tmpfifo0.OutputImage IsNot Nothing Then
                            SecondCCDState = 0 '正常
                            AppendInfoToTextBox("tmpCalibCB.Run()")
                            CogIPOneImageTool1.Run()
                            tmpCalibCB.Run()
                            tmpCogCalibCheckerboardTool.Run()
                            tmpPmalign1.Run()
                            Dim dTemp As Double = 0
                            Dim dTemp2 As String = ""

                            If tmpPmalign1.RunStatus.Result = CogToolResultConstants.Accept Then
                                If tmpPmalign.Results.Count > 0 Then
                                    dTemp = tmpPmalign.Results.Item(0).GetPose.TranslationX.ToString
                                    dTemp2 = Format(dTemp, "000.00")
                                    SendDataX(0) = dTemp
                                    strSendData += dTemp2 & ","
                                    dTemp = tmpPmalign.Results.Item(0).GetPose.TranslationY.ToString
                                    dTemp2 = Format(dTemp, "000.00")
                                    SendDataY(0) = dTemp
                                    strSendData += dTemp2 & ","
                                    dTemp = 0
                                    dTemp += tmpPmalign.Results.Item(0).GetPose.Rotation / Acos(-1) * 180
                                    dTemp2 = Format(dTemp, "000.00")
                                    SendDataR(0) = dTemp
                                    AppendInfoToTextBox(" SendDataR(0) = dTemp")
                                    strSendData += dTemp2 & ","
                                Else
                                    strSendData += "999" + ","
                                    strSendData += "999" + ","
                                    strSendData += "229.9,"
                                    strSendData += "0"
                                    SendDataX(0) = 999999.0

                                End If
                                '保存失败图片
                                If tmpPmalign.Results.Count < 1 Then
                                    Dim fileName As String = Format(Date.Now.Date, "yyyyMMdd") & Format(DateTime.Now.Ticks) & ".jpg"
                                    Dim filePath As String = gVisionFailedPath & Chanpin & "\" & Format(Date.Now.Date, "yyyyMMdd") & "\" & Chanpin & "\" & "Fail Image\"
                                    YSPic(CogRecordDisplay2, CogIPOneImageTool1, filePath, fileName)
                                End If
c:
                                If SecondCCDState = 2 Then
                                    strSendData += "999,999,0,0"
                                    SendDataX(0) = 999999.0
                                End If
                            Else
                                strSendData += "999,0,0,0"
                                SendDataX(0) = 999999.0
                            End If
                            strSendData += "" ' vbCrLf
                            AppendInfoToTextBox("Point" & StrReceData & ":" & vbCrLf & strSendData + vbCrLf)
                            Dim byteSend As Byte() = Encoding.ASCII.GetBytes(SendDataX(0) & "," & SendDataY(0) & "," & SendDataR(0) & vbCrLf)
                            MySocket.Send(byteSend)

                            TSRest.Text = (DateTime.Now.Ticks - __time.Ticks) / 10000 & "ms"

                            CogRecordDisplay2.Image = CogIPOneImageTool1.OutputImage
                            CogRecordDisplay2.Fit()
                            If tmpfifo0.Operator.FrameGrabber IsNot Nothing Then
                                CogRecordDisplay2.Record = tmpPmalign.CreateLastRunRecord
                            End If
                        Else
                            SecondCCDState = 3
                        End If

                    End If
                Else
                    SecondCCDState = 1
                End If
            Else
                SecondCCDState = 2
                GoTo c
                AppendInfoToTextBox("未连接摄像机！")
            End If
        Catch ex As Exception
            WriteInspecLog(TSLog, "SinglePointCameraProcess_1" & vbTab & ex.StackTrace.ToString)
            MsgBox(ex.StackTrace.ToString)
        End Try

d:
    End Sub

    Private Sub SinglePointCameraProcess_2(ByRef MySocket As Socket, ByVal StrReceData As String)
        Dim __time As DateTime = DateTime.Now
        AppendInfoToTextBox("SinglePointCameraProcess_2 run")
        Try
            Dim tmpfifo0 As CogAcqFifoTool = gTBCheck(3).Tools.Item("相机设定")
            Dim tmpCalibCB As CogCalibCheckerboardTool = gTBCheck(3).Tools.Item("CogCalibCheckerboardTool1")
            Dim tmpCogCalibCheckerboardTool As CogCalibNPointToNPointTool = gTBCheck(3).Tools.Item("CogCalibNPointToNPointTool1")
            Dim tmpPmalign1 As CogPMAlignTool = gTBCheck(3).Tools.Item("CogPMAlignTool1")
            Dim CogIPOneImageTool1 As CogIPOneImageTool = gTBCheck(3).Tools.Item("CogIPOneImageTool1")
            Dim tmpPmalign As CogPMAlignTool = tmpPmalign1
            Dim strErrorInfo As String = ""
            Dim strSendData As String = ""
            Dim bHasObject As Boolean = False
            If tmpfifo0.Operator.FrameGrabber IsNot Nothing Then
                AppendInfoToTextBox("FrameGrabber")
                If True Then
                    tmpfifo0.Run()
                    If tmpfifo0.OutputImage Is Nothing Then
                        AppendInfoToTextBox(tmpfifo0.RunStatus.Exception.ToString)
                        AppendInfoToTextBox(tmpfifo0.RunStatus.Message)
                        tmpfifo0.Run()
                        AppendInfoToTextBox("AcqBaseImage首次取相失败，再进行第二次取相")
                        If tmpfifo0.OutputImage Is Nothing Then
                            SecondCCDState = 2
                            GoTo c
                        Else
                            GoTo sucess
                        End If
                    Else
sucess:
                        If tmpfifo0.OutputImage IsNot Nothing Then
                            SecondCCDState = 0 '正常
                            AppendInfoToTextBox("tmpCalibCB.Run()")
                            CogIPOneImageTool1.Run()
                            tmpCalibCB.Run()
                            tmpCogCalibCheckerboardTool.Run()
                            tmpPmalign1.Run()
                            Dim dTemp As Double = 0
                            Dim dTemp2 As String = ""

                            If tmpPmalign1.RunStatus.Result = CogToolResultConstants.Accept Then
                                If tmpPmalign.Results.Count > 0 Then
                                    dTemp = tmpPmalign.Results.Item(0).GetPose.TranslationX.ToString
                                    dTemp2 = Format(dTemp, "000.00")
                                    SendDataX(0) = dTemp
                                    strSendData += dTemp2 & ","
                                    dTemp = tmpPmalign.Results.Item(0).GetPose.TranslationY.ToString
                                    dTemp2 = Format(dTemp, "000.00")
                                    SendDataY(0) = dTemp
                                    strSendData += dTemp2 & ","
                                    dTemp = 0
                                    dTemp += tmpPmalign.Results.Item(0).GetPose.Rotation / Acos(-1) * 180
                                    dTemp2 = Format(dTemp, "000.00")
                                    SendDataR(0) = dTemp
                                    AppendInfoToTextBox(" SendDataR(0) = dTemp")
                                    strSendData += dTemp2 & ","
                                Else
                                    strSendData += "999" + ","
                                    strSendData += "999" + ","
                                    strSendData += "229.9,"
                                    strSendData += "0"
                                    SendDataX(0) = 999999.0

                                End If
                                If tmpPmalign.Results.Count < 1 Then
                                    Dim fileName As String = Format(Date.Now.Date, "yyyyMMdd") & Format(DateTime.Now.Ticks) & ".jpg"
                                    Dim filePath As String = gVisionFailedPath & Chanpin & "\" & Format(Date.Now.Date, "yyyyMMdd") & "\" & Chanpin & "\" & "Fail Image\"
                                    YSPic(CogRecordDisplay2, CogIPOneImageTool1, filePath, fileName)
                                End If
c:
                                If SecondCCDState = 2 Then
                                    strSendData += "999,999,0,0"
                                    SendDataX(0) = 999999.0
                                End If
                            Else
                                strSendData += "999,0,0,0"
                                SendDataX(0) = 999999.0
                            End If
                            strSendData += "" ' vbCrLf
                            AppendInfoToTextBox("Point" & StrReceData & ":" & vbCrLf & strSendData + vbCrLf)
                            Dim byteSend As Byte() = Encoding.ASCII.GetBytes(SendDataX(0) & "," & SendDataY(0) & "," & SendDataR(0) & vbCrLf)
                            MySocket.Send(byteSend)

                            TSRest.Text = (DateTime.Now.Ticks - __time.Ticks) / 10000 & "ms"

                            CogRecordDisplay2.Image = CogIPOneImageTool1.OutputImage
                            CogRecordDisplay2.Fit()
                            If tmpfifo0.Operator.FrameGrabber IsNot Nothing Then
                                CogRecordDisplay2.Record = tmpPmalign.CreateLastRunRecord
                            End If
                        Else
                            SecondCCDState = 3
                        End If

                    End If
                Else
                    SecondCCDState = 1
                End If
            Else
                SecondCCDState = 2
                GoTo c
                AppendInfoToTextBox("未连接摄像机！")
            End If
        Catch ex As Exception
            WriteInspecLog(TSLog, "SinglePointCameraProcess_2" & vbTab & ex.StackTrace.ToString)
            MsgBox(ex.StackTrace.ToString)
        End Try

d:
    End Sub

    Private Sub SinglePointCameraProcess_3(ByRef MySocket As Socket, ByVal StrReceData As String)
        Dim __time As DateTime = DateTime.Now
        AppendInfoToTextBox("SinglePointCameraProcess_3 run")

        Try
            Dim tmpfifo0 As CogAcqFifoTool = gTBCheck(4).Tools.Item("相机设定")
            Dim tmpCalibCB As CogCalibCheckerboardTool = gTBCheck(4).Tools.Item("CogCalibCheckerboardTool1")
            Dim tmpCogCalibCheckerboardTool As CogCalibNPointToNPointTool = gTBCheck(4).Tools.Item("CogCalibNPointToNPointTool1")
            Dim tmpPmalign1 As CogPMAlignTool = gTBCheck(4).Tools.Item("CogPMAlignTool1")
            Dim CogIPOneImageTool1 As CogIPOneImageTool = gTBCheck(4).Tools.Item("CogIPOneImageTool1")
            Dim tmpPmalign As CogPMAlignTool = tmpPmalign1
            Dim strErrorInfo As String = ""
            Dim strSendData As String = ""
            Dim bHasObject As Boolean = False
            If tmpfifo0.Operator.FrameGrabber IsNot Nothing Then
                AppendInfoToTextBox("FrameGrabber")
                If True Then
                    tmpfifo0.Run()
                    If tmpfifo0.OutputImage Is Nothing Then
                        AppendInfoToTextBox(tmpfifo0.RunStatus.Exception.ToString)
                        AppendInfoToTextBox(tmpfifo0.RunStatus.Message)
                        tmpfifo0.Run()
                        AppendInfoToTextBox("AcqBaseImage首次取相失败，再进行第二次取相")
                        If tmpfifo0.OutputImage Is Nothing Then
                            SecondCCDState = 2
                            GoTo c
                        Else
                            GoTo sucess
                        End If
                    Else
sucess:
                        If tmpfifo0.OutputImage IsNot Nothing Then
                            SecondCCDState = 0 '正常
                            AppendInfoToTextBox("tmpCalibCB.Run()")
                            CogIPOneImageTool1.Run()
                            tmpCalibCB.Run()
                            tmpCogCalibCheckerboardTool.Run()
                            tmpPmalign1.Run()
                            Dim dTemp As Double = 0
                            Dim dTemp2 As String = ""

                            If tmpPmalign1.RunStatus.Result = CogToolResultConstants.Accept Then
                                If tmpPmalign.Results.Count > 0 Then
                                    dTemp = tmpPmalign.Results.Item(0).GetPose.TranslationX.ToString
                                    dTemp2 = Format(dTemp, "000.00")
                                    SendDataX(0) = dTemp
                                    strSendData += dTemp2 & ","
                                    dTemp = tmpPmalign.Results.Item(0).GetPose.TranslationY.ToString
                                    dTemp2 = Format(dTemp, "000.00")
                                    SendDataY(0) = dTemp
                                    strSendData += dTemp2 & ","
                                    dTemp = 0
                                    dTemp += tmpPmalign.Results.Item(0).GetPose.Rotation / Acos(-1) * 180
                                    dTemp2 = Format(dTemp, "000.00")
                                    SendDataR(0) = dTemp
                                    AppendInfoToTextBox(" SendDataR(0) = dTemp")
                                    strSendData += dTemp2 & ","
                                Else
                                    strSendData += "999" + ","
                                    strSendData += "999" + ","
                                    strSendData += "229.9,"
                                    strSendData += "0"
                                    SendDataX(0) = 999999.0
                                End If
                                If tmpPmalign.Results.Count < 1 Then
                                    Dim fileName As String = Format(Date.Now.Date, "yyyyMMdd") & Format(DateTime.Now.Ticks) & ".jpg"
                                    Dim filePath As String = gVisionFailedPath & Chanpin & "\" & Format(Date.Now.Date, "yyyyMMdd") & "\" & Chanpin & "\" & "Fail Image\"
                                    YSPic(CogRecordDisplay2, CogIPOneImageTool1, filePath, fileName)
                                End If
c:
                                If SecondCCDState = 2 Then
                                    strSendData += "999,999,0,0"
                                    SendDataX(0) = 999999.0
                                End If
                            Else
                                strSendData += "999,0,0,0"
                                SendDataX(0) = 999999.0
                            End If
                            strSendData += "" ' vbCrLf
                            AppendInfoToTextBox("Point" & StrReceData & ":" & vbCrLf & strSendData + vbCrLf)
                            Dim byteSend As Byte() = Encoding.ASCII.GetBytes(SendDataX(0) & "," & SendDataY(0) & "," & SendDataR(0) & vbCrLf)
                            MySocket.Send(byteSend)

                            TSRest.Text = (DateTime.Now.Ticks - __time.Ticks) / 10000 & "ms"

                            CogRecordDisplay2.Image = CogIPOneImageTool1.OutputImage
                            CogRecordDisplay2.Fit()
                            If tmpfifo0.Operator.FrameGrabber IsNot Nothing Then
                                CogRecordDisplay2.Record = tmpPmalign.CreateLastRunRecord
                            End If
                        Else
                            SecondCCDState = 3
                        End If

                    End If
                Else
                    SecondCCDState = 1
                End If
            Else
                SecondCCDState = 2
                GoTo c
                AppendInfoToTextBox("未连接摄像机！")
            End If
        Catch ex As Exception
            WriteInspecLog(TSLog, "SinglePointCameraProcess_3" & vbTab & ex.StackTrace.ToString)
            MsgBox(ex.StackTrace.ToString)
        End Try

d:
    End Sub

    Private Sub SinglePointCameraProcess_4(ByRef MySocket As Socket, ByVal StrReceData As String)
        Dim __time As DateTime = DateTime.Now
        AppendInfoToTextBox("SinglePointCameraProcess_4 run")

        Try
            Dim tmpfifo0 As CogAcqFifoTool = gTBCheck(5).Tools.Item("相机设定")
            Dim tmpCalibCB As CogCalibCheckerboardTool = gTBCheck(5).Tools.Item("CogCalibCheckerboardTool1")
            Dim tmpCogCalibCheckerboardTool As CogCalibNPointToNPointTool = gTBCheck(5).Tools.Item("CogCalibNPointToNPointTool1")
            Dim tmpPmalign1 As CogPMAlignTool = gTBCheck(5).Tools.Item("CogPMAlignTool1")
            Dim CogIPOneImageTool1 As CogIPOneImageTool = gTBCheck(5).Tools.Item("CogIPOneImageTool1")
            Dim tmpPmalign As CogPMAlignTool = tmpPmalign1
            Dim strErrorInfo As String = ""
            Dim strSendData As String = ""
            Dim bHasObject As Boolean = False
            If tmpfifo0.Operator.FrameGrabber IsNot Nothing Then
                AppendInfoToTextBox("FrameGrabber")
                If True Then
                    tmpfifo0.Run()
                    If tmpfifo0.OutputImage Is Nothing Then
                        AppendInfoToTextBox(tmpfifo0.RunStatus.Exception.ToString)
                        AppendInfoToTextBox(tmpfifo0.RunStatus.Message)
                        tmpfifo0.Run()
                        AppendInfoToTextBox("AcqBaseImage首次取相失败，再进行第二次取相")
                        If tmpfifo0.OutputImage Is Nothing Then
                            SecondCCDState = 2
                            GoTo c
                        Else
                            GoTo sucess
                        End If
                    Else
sucess:
                        If tmpfifo0.OutputImage IsNot Nothing Then
                            SecondCCDState = 0 '正常
                            AppendInfoToTextBox("tmpCalibCB.Run()")
                            CogIPOneImageTool1.Run()
                            tmpCalibCB.Run()
                            tmpCogCalibCheckerboardTool.Run()
                            tmpPmalign1.Run()
                            Dim dTemp As Double = 0
                            Dim dTemp2 As String = ""

                            If tmpPmalign1.RunStatus.Result = CogToolResultConstants.Accept Then
                                If tmpPmalign.Results.Count > 0 Then
                                    dTemp = tmpPmalign.Results.Item(0).GetPose.TranslationX.ToString
                                    dTemp2 = Format(dTemp, "000.00")
                                    SendDataX(0) = dTemp
                                    strSendData += dTemp2 & ","
                                    dTemp = tmpPmalign.Results.Item(0).GetPose.TranslationY.ToString
                                    dTemp2 = Format(dTemp, "000.00")
                                    SendDataY(0) = dTemp
                                    strSendData += dTemp2 & ","
                                    dTemp = 0
                                    dTemp += tmpPmalign.Results.Item(0).GetPose.Rotation / Acos(-1) * 180
                                    dTemp2 = Format(dTemp, "000.00")
                                    SendDataR(0) = dTemp
                                    AppendInfoToTextBox(" SendDataR(0) = dTemp")
                                    strSendData += dTemp2 & ","
                                Else
                                    strSendData += "999" + ","
                                    strSendData += "999" + ","
                                    strSendData += "229.9,"
                                    strSendData += "0"
                                    SendDataX(0) = 999999.0
                                End If
                                If tmpPmalign.Results.Count < 1 Then
                                    Dim fileName As String = Format(Date.Now.Date, "yyyyMMdd") & Format(DateTime.Now.Ticks) & ".jpg"
                                    Dim filePath As String = gVisionFailedPath & Chanpin & "\" & Format(Date.Now.Date, "yyyyMMdd") & "\" & Chanpin & "\" & "Fail Image\"
                                    YSPic(CogRecordDisplay2, CogIPOneImageTool1, filePath, fileName)
                                End If
c:
                                If SecondCCDState = 2 Then
                                    strSendData += "999,999,0,0"
                                    SendDataX(0) = 999999.0
                                End If
                            Else
                                strSendData += "999,0,0,0"
                                SendDataX(0) = 999999.0
                            End If
                            strSendData += "" ' vbCrLf
                            AppendInfoToTextBox("Point" & StrReceData & ":" & vbCrLf & strSendData + vbCrLf)
                            Dim byteSend As Byte() = Encoding.ASCII.GetBytes(SendDataX(0) & "," & SendDataY(0) & "," & SendDataR(0) & vbCrLf)
                            MySocket.Send(byteSend)

                            TSRest.Text = (DateTime.Now.Ticks - __time.Ticks) / 10000 & "ms"

                            CogRecordDisplay2.Image = CogIPOneImageTool1.OutputImage
                            CogRecordDisplay2.Fit()
                            If tmpfifo0.Operator.FrameGrabber IsNot Nothing Then
                                CogRecordDisplay2.Record = tmpPmalign.CreateLastRunRecord
                            End If
                        Else
                            SecondCCDState = 3
                        End If

                    End If
                Else
                    SecondCCDState = 1
                End If
            Else
                SecondCCDState = 2
                GoTo c
                AppendInfoToTextBox("未连接摄像机！")
            End If
        Catch ex As Exception
            WriteInspecLog(TSLog, "SinglePointCameraProcess_4" & vbTab & ex.StackTrace.ToString)
            MsgBox(ex.StackTrace.ToString)
        End Try

d:
    End Sub

    Private Sub RobotParameterSet(ByRef MySocket As Socket, ByVal StrReceData As String)
        Dim strSendData As String = ""

        strSendData = ""
        strSendData += CStr(Pget(0).XPosCompensate) + "," + CStr(Pget(0).YPosCompensate) + "," + CStr(Pget(0).ZPosCompensate) + ","
        strSendData += CStr(Pget(1).XPosCompensate) + "," + CStr(Pget(1).YPosCompensate) + "," + CStr(Pget(1).ZPosCompensate) + ","
        strSendData += CStr(Pget(4).XPosCompensate) + "," + CStr(Pget(4).YPosCompensate) + "," + CStr(Pget(4).ZPosCompensate) + ","
        strSendData += CStr(Pget(5).XPosCompensate) + "," + CStr(Pget(5).YPosCompensate) + "," + CStr(Pget(5).ZPosCompensate) + ","
        strSendData += CStr(newset(0)) + "," + CStr(newset(1)) + "," + CStr(ADD_Screw_Count) + "," + CStr(CurScrewPara.PointCount) + "," + CStr(KESU) + "," + CStr(Photo3_flag) & "," & Retry_Times
        AppendInfoToTextBox("send:S:" + Chanpin + "," + strSendData + vbCrLf)
        strSendData = strSendData + vbCrLf
        Dim byteSend As Byte() = Encoding.ASCII.GetBytes(Chanpin + "," + strSendData)
        MySocket.Send(byteSend)

    End Sub

#End Region

#Region "屏幕按键指令"

    Private Sub TSGrab1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TSGrab1.Click '单独拍摄1
        Try
            Dim Cur_Cam_Num As Integer = gCheckIndex - 1 '当前相机变量
            fifo(Cur_Cam_Num).Run()
            '        CogRecordDisplay1.Image = fifo(Cur_Cam_Num).OutputImage
            '      CogRecordDisplay1.Fit()
        Catch ex As Exception
            MsgBox("拍摄出错！" & ex.Message)
        End Try
    End Sub

    Private Sub TSGrab2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
        Try
            Dim Cur_Cam_Num As Integer = 1 '当前相机变量
            fifo(Cur_Cam_Num).Run()
            'CogRecordDisplay2.Image = fifo(Cur_Cam_Num).OutputImage
            'CogRecordDisplay2.Fit()
        Catch ex As Exception
            MsgBox("拍摄出错！" & ex.Message)
        End Try
    End Sub

    Private Sub TSGrab3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
        Try
            Dim Cur_Cam_Num As Integer = 2 '当前相机变量
            fifo(Cur_Cam_Num).Run()
            'CogRecordDisplay3.Image = fifo(Cur_Cam_Num).OutputImage
            'CogRecordDisplay3.Fit()
        Catch ex As Exception
            MsgBox("拍摄出错！" & ex.Message)
        End Try
    End Sub

    Private Sub TSGrab4_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
        Try
            Dim Cur_Cam_Num As Integer = 3 '当前相机变量
            fifo(Cur_Cam_Num).Run()
            'CogRecordDisplay4.Image = fifo(Cur_Cam_Num).OutputImage
            'CogRecordDisplay4.Fit()
        Catch ex As Exception
            MsgBox("拍摄出错！" & ex.Message)
        End Try
    End Sub

    Private Sub BWGrab1_DoWork(ByVal sender As System.Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles BWGrab1.DoWork
        Try
            Dim Cur_Cam_Num As Integer = gCheckIndex - 1 '当前相机变量
            While TSGrabContinues1.Text = "停止拍摄"
                fifo(Cur_Cam_Num).Run()
                '      CogRecordDisplay1.Image = fifo(Cur_Cam_Num).OutputImage
                '     CogRecordDisplay1.Fit()
                wait(1)
            End While
        Catch ex As Exception
            MsgBox("连续拍摄出错！" & ex.Message)
        End Try
    End Sub

    Private Sub BWGrab2_DoWork(ByVal sender As System.Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles BWGrab2.DoWork
        'Try
        '    Dim Cur_Cam_Num As Integer = 1 '当前相机变量
        '    While TSGrabContinues2.Text = "停止拍摄"
        '        fifo(Cur_Cam_Num).Run()
        '        CogRecordDisplay2.Image = fifo(Cur_Cam_Num).OutputImage
        '        CogRecordDisplay2.Fit()
        '        wait(1)
        '    End While
        'Catch ex As Exception
        '    MsgBox("连续拍摄出错！" & ex.Message)
        'End Try
    End Sub

    'Private Sub BWGrab3_DoWork(ByVal sender As System.Object, ByVal e As System.ComponentModel.DoWorkEventArgs)
    '    Try
    '        Dim Cur_Cam_Num As Integer = 2 '当前相机变量
    '        While TSGrabContinues3.Text = "停止拍摄"
    '            fifo(Cur_Cam_Num).Run()
    '            CogRecordDisplay3.Image = fifo(Cur_Cam_Num).OutputImage
    '            CogRecordDisplay3.Fit()
    '            wait(1)
    '        End While
    '    Catch ex As Exception
    '        MsgBox("连续拍摄出错！" & ex.Message)
    '    End Try
    'End Sub

    'Private Sub BWGrab4_DoWork(ByVal sender As System.Object, ByVal e As System.ComponentModel.DoWorkEventArgs)
    '    Try
    '        Dim Cur_Cam_Num As Integer = 3 '当前相机变量
    '        While TSGrabContinues4.Text = "停止拍摄"
    '            fifo(Cur_Cam_Num).Run()
    '            CogRecordDisplay4.Image = fifo(Cur_Cam_Num).OutputImage
    '            CogRecordDisplay4.Fit()
    '            wait(1)
    '        End While
    '    Catch ex As Exception
    '        MsgBox("连续拍摄出错！" & ex.Message)
    '    End Try
    'End Sub
    Private Sub TSGrabContinues1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TSGrabContinues1.Click
        If TSGrabContinues1.Text = "连续拍摄" Then
            TSGrabContinues1.Text = "停止拍摄"
            If Not BWGrab1.IsBusy Then
                BWGrab1.RunWorkerAsync()
            End If
            MenuStrip1.Enabled = False
            ToolStrip5.Enabled = False
        Else
            TSGrabContinues1.Text = "连续拍摄"
            MenuStrip1.Enabled = True
            ToolStrip5.Enabled = True
        End If
    End Sub

    'Private Sub TSGrabContinues2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
    '    If TSGrabContinues2.Text = "连续拍摄" Then
    '        TSGrabContinues2.Text = "停止拍摄"
    '        If Not BWGrab2.IsBusy Then
    '            BWGrab2.RunWorkerAsync()
    '        End If
    '        MenuStrip1.Enabled = False
    '        ToolStrip5.Enabled = False
    '    Else
    '        TSGrabContinues2.Text = "连续拍摄"
    '        MenuStrip1.Enabled = True
    '        ToolStrip5.Enabled = True
    '    End If
    'End Sub
    'Private Sub TSGrabContinues3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
    '    If TSGrabContinues3.Text = "连续拍摄" Then
    '        TSGrabContinues3.Text = "停止拍摄"
    '        'If Not BWGrab3.IsBusy Then
    '        '    BWGrab3.RunWorkerAsync()
    '        'End If
    '        MenuStrip1.Enabled = False
    '        ToolStrip5.Enabled = False
    '    Else
    '        TSGrabContinues3.Text = "连续拍摄"
    '        MenuStrip1.Enabled = True
    '        ToolStrip5.Enabled = True
    '    End If
    'End Sub
    'Private Sub TSGrabContinues4_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
    '    If TSGrabContinues4.Text = "连续拍摄" Then
    '        TSGrabContinues4.Text = "停止拍摄"
    '        'If Not BWGrab4.IsBusy Then
    '        '    BWGrab4.RunWorkerAsync()
    '        'End If
    '        MenuStrip1.Enabled = False
    '        ToolStrip5.Enabled = False
    '    Else
    '        TSGrabContinues4.Text = "连续拍摄"
    '        MenuStrip1.Enabled = True
    '        ToolStrip5.Enabled = True
    '    End If
    'End Sub
    Private Sub TsOpenFile1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TsOpenFile1.Click
        Try
            Dim gImageOpen As New CogImageFileTool
            OpenFileDialog1.Filter = "Single Image (*.bmp)|*.bmp"
            If OpenFileDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then
                gImageOpen.Operator.Open(OpenFileDialog1.FileName, CogImageFileModeConstants.Read)
                gImageOpen.Run()
                '       CogRecordDisplay1.Image = gImageOpen.OutputImage
            End If
        Catch ex As Exception

        End Try
    End Sub

    'Private Sub ToolStripButton3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
    '    Try
    '        Dim gImageOpen As New CogImageFileTool
    '        OpenFileDialog1.Filter = "Single Image (*.bmp)|*.bmp"
    '        If OpenFileDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then
    '            gImageOpen.Operator.Open(OpenFileDialog1.FileName, CogImageFileModeConstants.Read)
    '            gImageOpen.Run()
    '            CogRecordDisplay2.Image = gImageOpen.OutputImage
    '        End If

    '    Catch ex As Exception

    '    End Try
    'End Sub

    'Private Sub TsOpenFile3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
    '    Try
    '        Dim gImageOpen As New CogImageFileTool
    '        OpenFileDialog1.Filter = "Single Image (*.bmp)|*.bmp"
    '        If OpenFileDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then
    '            gImageOpen.Operator.Open(OpenFileDialog1.FileName, CogImageFileModeConstants.Read)
    '            gImageOpen.Run()
    '            CogRecordDisplay3.Image = gImageOpen.OutputImage
    '        End If

    '    Catch ex As Exception

    '    End Try
    'End Sub

    'Private Sub TsOpenFile4_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
    '    Try
    '        Dim gImageOpen As New CogImageFileTool
    '        OpenFileDialog1.Filter = "Single Image (*.bmp)|*.bmp"
    '        If OpenFileDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then
    '            gImageOpen.Operator.Open(OpenFileDialog1.FileName, CogImageFileModeConstants.Read)
    '            gImageOpen.Run()
    '            CogRecordDisplay4.Image = gImageOpen.OutputImage
    '        End If

    '    Catch ex As Exception

    '    End Try
    'End Sub
    Private Sub TSRun1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TSRun1.Click
        Try
            Dim Cur_Cam_Num As Integer = gCheckIndex - 1 '当前相机变量
            gTBCheck(Cur_Cam_Num).Run() '运行图像处理工具
            '显示
            '     CogRecordDisplay1.Image = fifo(Cur_Cam_Num).OutputImage
            '      CogRecordDisplay1.Fit()
            '     CogRecordDisplay1.Record = gTBCheck(Cur_Cam_Num).CreateLastRunRecord
        Catch ex As Exception

        End Try
    End Sub

    'Private Sub TSRun2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
    '    Try
    '        Dim Cur_Cam_Num As Integer = 1 '当前相机变量
    '        gTBCheck(Cur_Cam_Num).Run() '运行图像处理工具
    '        '显示
    '        CogRecordDisplay2.Image = fifo(Cur_Cam_Num).OutputImage
    '        CogRecordDisplay2.Fit()
    '        CogRecordDisplay2.Record = gTBCheck(Cur_Cam_Num).CreateLastRunRecord
    '    Catch ex As Exception

    '    End Try
    'End Sub

#End Region

    Private Sub SNInputBox_KeyDown(ByVal Sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles SNInputBox.KeyDown

        Try
            'If e.KeyCode = Keys.Enter Then
            '   SNInputProcess(SNInputBox.Text)
            '    SNInputBox.Text = ""
            'End If
        Catch ex As Exception
            AppendInfoToTextBox("SNInputBox:" & ex.Message.ToString)
            'AppendInfoToTextBox("服务器连接失败或机器人连接异常或SN错误！")
            SNInputBox.Text = ""
        End Try

    End Sub

    ''' <summary>
    ''' 获取SN所对应的机型
    ''' </summary>
    ''' <param name="SN"></param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Private Function MES_BaseDataRequest(ByVal SN As String) As String
        Dim result As String = ""
        Dim SendData As String
        Try
            Dim H_GUID As String = "ActGUID"                              '填实际的GUID值，全局唯一标识符
            Dim H_OP As String = "ATScrewGetInfoBAT"                         '接口名
            Dim H_ACTION As String = "ActStation" 'machineInfo.Station                  '站别
            Dim G_OP_LINE As String = "TD03" 'machineInfo.Line                    '线别
            Dim G_USER As String = "123"                                  '??
            Dim G_OP_PC As String = "" 'machineInfo.Fixture                   '治具号
            Dim G_SN As String = SN                                       'sn
            'Dim H_TOKEN As String = "CPMKS9kmphNRwTUy0AKSWBketkENoTB6"    '设备的H_TOKEN
            Dim H_TOKEN As String = ""    '设备的H_TOKEN
            SendData = "{""HEAD"":{""H_GUID"":""" & H_GUID & """,""H_SRC_SYS"":"""",""H_OP"":""" & H_OP & """,""H_TOKEN"":""" & H_TOKEN & """,""H_ACTION"":""" & H_ACTION & """},""MAIN"":{""H_OP"":""" & H_OP & """,""H_ACTION"":""" & H_ACTION & """,""G_OP_LINE"":""" & G_OP_LINE & """,""G_WS"":""" & H_ACTION & """,""G_USER"":""" & G_USER & """,""G_OP_PC"":""" & G_OP_PC & """,""G_SN"":""" & G_SN & """,""G_IP"":""ActIP""}}"
            AppendInfoToTextBox("发送信息给MES：" & SendData)
            Dim MESIP As String = ProductFreTime
            result = MakeRequest2(MESIP, "", 10000, SendData)
        Catch ex As Exception
            AddErrMsgToTextBox(ex.Message.ToString & ex.StackTrace.ToString)
            AppendInfoToTextBox(ex.Message.ToString & ex.StackTrace.ToString)
        End Try
        Return result
    End Function

    ''' <summary>
    ''' 格式示例接口
    ''' </summary>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Private Function MES_SCADA_FormateDemo() As String
        Dim result As String = ""
        Dim SendData As String
        Try
            Dim H_GUID As String = "ActGUID" '填实际的GUID值，全局唯一标识符
            Dim H_OP As String = "SCADA_FormateDemo"                      '接口名
            Dim USER As String = TextBox_OPID.Text                        '实际的操作人员工号
            Dim EQSN As String = machineInfo.Device_id                    '设备编号，请工厂提供
            Dim TESTTYPE As String = "PASS"                               '测试类型，PASS为测试PASS的格式，否则为测试FAIL的格式
            Dim HostName As String = machineInfo.Family                   '设备的主机名
            Dim IP As String = machineInfo.IP                             '设备的IP
            Dim H_TOKEN As String = "CPMKS9kmphNRwTUy0AKSWBketkENoTB6"    '设备的H_TOKEN
            SendData = "{""HEAD"":{""H_GUID"":""" & H_GUID & """,""H_SRC_SYS"":"""",""H_OP"":""" & H_OP & """,""H_TOKEN"":""" & H_TOKEN & """},""MAIN"":{""USER"":""" & USER & """,""EQSN"":""" & EQSN & """,""TESTTYPE"":""" & TESTTYPE & """,""HostName"":""" & HostName & """,""IP"":""" & IP & """}}"
            AppendInfoToTextBox("发送信息给MES：" & SendData)
            Dim MESIP As String = ProductFreTime
            result = MakeRequest2(MESIP, "", 10000, SendData)
        Catch ex As Exception
            AppendInfoToTextBox(ex.Message.ToString & ex.StackTrace.ToString)
        End Try
        Return result
    End Function

    ''' <summary>
    ''' mes数据访问
    ''' </summary>
    ''' <param name="parameters"></param>
    ''' <param name="timeOut"></param>
    ''' <param name="PostData"></param>
    ''' <returns></returns>
    Public Function MakeRequest2(URL As String, parameters As String, timeOut As Integer, PostData As String) As String
        Dim responseValue As String = String.Empty
        Try
            Dim request As HttpWebRequest = CType(WebRequest.Create(URL + parameters), HttpWebRequest)
            request.Method = HttpVerb.POST.ToString
            request.ContentLength = 0
            request.ContentType = "application/json"
            request.Timeout = timeOut
            If String.IsNullOrEmpty(PostData) = False Then
                Dim bytes() As Byte = Encoding.UTF8.GetBytes(PostData)
                request.ContentLength = bytes.Length
                Using writeStream As Stream = request.GetRequestStream()
                    writeStream.Write(bytes, 0, bytes.Length)
                End Using
            End If

            Using response As HttpWebResponse = CType(request.GetResponse(), HttpWebResponse)

                If response.StatusCode <> HttpStatusCode.OK Then
                    Dim message As String = String.Format("Request failed. Received HTTP {0}", response.StatusCode)
                    AppendInfoToTextBox("MES访问异常：" & message)
                End If
                Using responseStream As Stream = response.GetResponseStream()
                    If responseStream IsNot Nothing Then
                        Using reader As StreamReader = New StreamReader(responseStream)
                            responseValue = reader.ReadToEnd()
                        End Using
                    End If
                End Using
            End Using
        Catch ex As Exception
            MsgBox(ex.Message)
            AppendInfoToTextBox(ex.Message)
            responseValue = ""
        End Try
        Return responseValue
    End Function

    ''' <summary>
    ''' 根据SN获取尺寸和机型
    ''' </summary>
    ''' <param name="SN"></param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Public Function GetInfoBySN(ByVal SN) As String
        Dim Info As String = ";"
        Try
            Dim portal As GetModel = New GetModel
            Info = portal.GetModelResponse(SN).LCMSize + ";" + portal.GetModelResponse(SN).Model
        Catch ex As Exception
            MsgBox("GetInfoBySN:" & ex.Message.ToString & ex.StackTrace.ToString)
        End Try
        Return Info
        'Dim Size As String = ""
        'Try
        '    '创建HttpWebRequest 实例，使用WebRequest.Create
        '    Dim webRequest As HttpWebRequest = CType(Net.WebRequest.Create(url), HttpWebRequest)
        '    webRequest.ContentType = "text/xml;charset=utf-8"
        '    webRequest.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.1.4322)"
        '    '发送请求
        '    webRequest.Method = "POST"
        '    '编码
        '    Dim soap As String = "<?xml version='1.0' encoding='utf-8' ?>"
        '    soap += "<soap:Envelope xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/'>"
        '    soap += "<soap:Body>"
        '    soap += "<GetModelResponse xmlns='http://tempuri.org/'>"
        '    soap += "<CustSN>" + SN + "</CustSN>"
        '    soap += "</GetModelResponse>"
        '    soap += "</soap:Body>"
        '    soap += "</soap:Envelope>"
        '    webRequest.Headers("SoapAction") = "http://tempuri.org/GetModelResponse"
        '    '字符转字节
        '    Dim bytes() As Byte = Encoding.UTF8.GetBytes(soap)
        '    Dim writer As Stream = webRequest.GetRequestStream()
        '    writer.Write(bytes, 0, bytes.Length)
        '    Dim hwRes As HttpWebResponse = CType(webRequest.GetResponse(), HttpWebResponse)
        '    'Dim xmlr As XmlTextReader = New XmlTextReader(My.Application.Info.DirectoryPath & "/1.xml")
        '    Dim xmlr As XmlTextReader = New XmlTextReader(hwRes.GetResponseStream())
        '    writer.Flush()
        '    writer.Close()
        '    While xmlr.Read()
        '        If xmlr.NodeType = System.Xml.XmlNodeType.Element And xmlr.LocalName.Equals("LCMSize") Then
        '            xmlr.Read()
        '            Size = xmlr.Value.Trim()
        '            If Size <> "" And Size IsNot Nothing Then
        '                xmlr.Close()
        '                Return Size
        '            End If
        '        End If
        '    End While
        'Catch ex As Exception
        '    MsgBox("GetInfoBySN:" & ex.Message.ToString & ex.StackTrace.ToString)
        'End Try
        'Return Size
    End Function

    Private Sub ManualInput_KeyDown(ByVal Sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles ManualInput.KeyDown
        Try
            If e.KeyCode = Keys.Enter Then
                'Dim chanpin As String = ManualInput.Text

                'AppendInfoToTextBox(chanpin)
                'TCmbPro.Text = UCase(chanpin)
                'SNInputBox.Text = ""
                'AppendInfoToTextBox(ManualInput.Text)
                'TCmbPro.Text = UCase(ManualInput.Text)
                'If newset(2) = True Then
                '    SP1.Write(UCase(ManualInput.Text))
                'End If
                ''SecondRobotProduct = UCase(ManualInput.Text)
                'SN_Socket.Send(Encoding.ASCII.GetBytes(UCase(ManualInput.Text) & vbCrLf))
                'ManualInput.Text = ""
                'If TCmbPro.Text <> "" Then
                '    InitSetting()
                '    initPro(TCmbPro.Text)
                'Else
                '    MsgBox("请选择产品")
                'End If
                Can_Barcode = True
                Dim sn As String = ManualInput.Text
                ScanSNAndMESRequest(sn)
            End If
        Catch
            MsgBox("机器人连接异常！")
        End Try

    End Sub

    Dim cn As OleDbConnection
    Dim da As OleDbDataAdapter
    Dim ds As DataSet
    'Sub LoadAccess()
    '    Try
    '        Dim cnStr As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source= Tool\" & TCmbPro.Text & "\robot_point.accdb;Persist Security Info=False"
    '        'MsgBox(cnStr)
    '        cn = New OleDbConnection(cnStr)
    '        Dim sql As String = "select * from domino" '产品表单模板名字'产品表单模板名字"
    '        da = New OleDbDataAdapter(sql, cn)
    '        ds = New DataSet
    '        da.Fill(ds, "grade")

    '    Catch
    '        AddInfoToTextBox("LoadAccess :ACCESS查询失败！")
    '    End Try
    'End Sub
    ''' <summary>
    ''' 将cad_point 点位计算并储存到robot_point中
    ''' </summary>
    ''' <remarks></remarks>
    Public Sub CadToRobot()

        Dim proname As String = "cad_point"
        Dim sql As String = "select * from " & proname & " where Product='" & Chanpin & "'" '产品表单模板名字'产品表单模板名字"
        ds = New DataSet
        ds = SearchMysql(sql)
        '获取cad_point 数据库XY点位
        For w = 0 To 33
            Dim m As Integer = 2 * w
            pointCAD(m) = Val(ds.Tables(0).Rows(w)(2))
            pointCAD(m + 1) = Val(ds.Tables(0).Rows(w)(3))
        Next

        '提取1~33点位Z轴数据
        For k = 4 To 33
            pointCAD_Z(k - 4) = Val(ds.Tables(0).Rows(k)(4))
        Next

        '提取1~33点位C轴数据
        For k = 4 To 33
            pointCAD_C(k - 4) = Val(ds.Tables(0).Rows(k)(5))
        Next
        ''提取1~33点位姿态数据
        'For k = 4 To 33
        '    pointCAD_FLG1(k - 4) = Val(ds.Tables(0).Rows(k)(6))
        'Next
        If bzw = 2 Then
            For w = 0 To 3
                pointCAD(w) = temp(w)   ' temp(w)为机器人上传拍照点位
            Next
        End If

        Dim ph1x As Double = pointCAD(0) - pointCAD(4)
        Dim ph1y As Double = pointCAD(1) - pointCAD(5)
        Dim ph2x As Double = pointCAD(2) - pointCAD(6)
        Dim ph2y As Double = pointCAD(3) - pointCAD(7)
        bzw = 1

        TwoPointurn(ph1x, ph1y, ph2x, ph2y)

        Dim s As String = ""
        Dim i
        Dim q

        For i = 0 To 59 '获取计算的偏差结果
            resu(i) = Val(resu(i)) + Val(pointCAD(i + 8))
        Next

        '将点位写入 robot_point 数据库
        Dim Sql2 As String = ""

        For k = 0 To 29
            i = 2 * k
            Dim point As String
            q = k + 1
            If q >= 10 Then
                point = "set" & q
            Else
                point = "set0" & q
            End If

            Sql2 = "update robot_point set x=" & resu(i) & ",y=" & resu(i + 1) & ",z=" & pointCAD_Z(k) & ",c=" & pointCAD_C(k) & " where pointname = '" & point & " ' and Product='" & Chanpin & "'"
            HandleMysql(Sql2)
        Next

    End Sub

    Public Function TwoPointurn(ByVal x1, ByVal y1, ByVal x3, ByVal y3)
        '函数用法：20个输入参数，前六个是拍照点PMA工具传过来的偏移量。
        '所有参与的数据必须为同一坐标系。
        Dim xy As InputXY
        Dim returnxy As returnXY
        Dim L31, L31_, L41, L51, L61, L71, temp_returnX1, temp_returnY1, temp_returnR1 As Double
        Dim L81, L91, LA1, LB1, LC1, LD1, LE1, LF1, LG1, LH1, LI1, LJ1, LK1, LL1, LM1, LN1, LO1, LP1, LQ1, LR1, LS1, LT1, LU1, LV1, LW1, LX1 As Double
        Dim A41, A51, A61, A71, A81, A91, AA1, AB1, AC1, AD1, AE1, AF1, AG1, AH1, AI1, AJ1, AK1, AL1, AM1, AN1, AO1, AP1, AQ1, AR1, AS1, AT1, AU1, AV1, AW1, AX1 As Double

        Dim w As Integer

        For w = 0 To 59
        Next
        xy = New InputXY(pointCAD)

        L31 = Sqrt(Pow((xy.X03 - xy.X01), 2) + Pow((xy.y03 - xy.y01), 2))
        L31_ = Sqrt(Pow((xy.X03 + x3 - xy.X01 - x1), 2) + Pow((xy.y03 + y3 - xy.y01 - y1), 2))

        If bzw = 1 Or bzw = 2 Then
            If Abs(L31 - L31_) > Pget(2).ZPosCompensate Then
                MsgBox("两点距离差值过大:" & Abs(L31 - L31_))
                returnxy.X1 = 900
                returnxy.Y1 = 900
                returnxy.X2 = 900
                returnxy.Y2 = 900
                returnxy.X3 = 900
                returnxy.Y3 = 900
                returnxy.X4 = 900
                returnxy.Y4 = 900
                returnxy.X5 = 900
                returnxy.Y5 = 900
                returnxy.X6 = 900
                returnxy.Y6 = 900
                returnxy.X7 = 900
                returnxy.Y7 = 900
                returnxy.X8 = 900
                returnxy.Y8 = 900
                returnxy.X9 = 900
                returnxy.Y9 = 900
                returnxy.X10 = 900
                returnxy.Y10 = 900
                returnxy.X11 = 900
                returnxy.Y11 = 900
                returnxy.X12 = 900
                returnxy.Y12 = 900
                returnxy.X13 = 900
                returnxy.Y13 = 900
                returnxy.X14 = 900
                returnxy.Y14 = 900
                returnxy.X15 = 900
                returnxy.Y15 = 900
                returnxy.X16 = 900
                returnxy.Y16 = 900
                returnxy.X17 = 900
                returnxy.Y17 = 900
                returnxy.X18 = 900
                returnxy.Y18 = 900
                returnxy.X19 = 900
                returnxy.Y19 = 900
                returnxy.X20 = 900
                returnxy.Y20 = 900
                returnxy.X21 = 900
                returnxy.Y21 = 900
                returnxy.X22 = 900
                returnxy.Y22 = 900
                returnxy.X23 = 900
                returnxy.Y23 = 900
                returnxy.X24 = 900
                returnxy.Y24 = 900
                returnxy.X25 = 900
                returnxy.Y25 = 900
                returnxy.X26 = 900
                returnxy.Y26 = 900
                returnxy.X27 = 900
                returnxy.Y27 = 900
                returnxy.X28 = 900
                returnxy.Y28 = 900
                returnxy.X29 = 900
                returnxy.Y29 = 900
                returnxy.X30 = 900
                returnxy.Y30 = 900
                GoTo eend
            End If
        Else
            If Abs(L31 - L31_) > Pget(2).ZPosCompensate Or x1 < Pget(2).XPosCompensate Or x1 > Pget(2).YPosCompensate Or x3 < Pget(2).XPosCompensate Or x3 > Pget(2).YPosCompensate Then
                AppendInfoToTextBox("两点间偏差过大：" & Abs(L31 - L31_) & vbCrLf)
                returnxy.X1 = 900
                returnxy.Y1 = 900
                returnxy.X2 = 900
                returnxy.Y2 = 900
                returnxy.X3 = 900
                returnxy.Y3 = 900
                returnxy.X4 = 900
                returnxy.Y4 = 900
                returnxy.X5 = 900
                returnxy.Y5 = 900
                returnxy.X6 = 900
                returnxy.Y6 = 900
                returnxy.X7 = 900
                returnxy.Y7 = 900
                returnxy.X8 = 900
                returnxy.Y8 = 900
                returnxy.X9 = 900
                returnxy.Y9 = 900
                returnxy.X10 = 900
                returnxy.Y10 = 900
                returnxy.X11 = 900
                returnxy.Y11 = 900
                returnxy.X12 = 900
                returnxy.Y12 = 900
                returnxy.X13 = 900
                returnxy.Y13 = 900
                returnxy.X14 = 900
                returnxy.Y14 = 900
                returnxy.X15 = 900
                returnxy.Y15 = 900
                returnxy.X16 = 900
                returnxy.Y16 = 900
                returnxy.X17 = 900
                returnxy.Y17 = 900
                returnxy.X18 = 900
                returnxy.Y18 = 900
                returnxy.X19 = 900
                returnxy.Y19 = 900
                returnxy.X20 = 900
                returnxy.Y20 = 900
                returnxy.X21 = 900
                returnxy.Y21 = 900
                returnxy.X22 = 900
                returnxy.Y22 = 900
                returnxy.X23 = 900
                returnxy.Y23 = 900
                returnxy.X24 = 900
                returnxy.Y24 = 900
                returnxy.X25 = 900
                returnxy.Y25 = 900
                returnxy.X26 = 900
                returnxy.Y26 = 900
                returnxy.X27 = 900
                returnxy.Y27 = 900
                returnxy.X28 = 900
                returnxy.Y28 = 900
                returnxy.X29 = 900
                returnxy.Y29 = 900
                returnxy.X30 = 900
                returnxy.Y30 = 900
                GoTo eend
            End If
        End If
        L41 = Sqrt(Pow((xy.X04 - xy.X01), 2) + Pow((xy.y04 - xy.y01), 2))

        L51 = Sqrt(Pow((xy.X05 - xy.X01), 2) + Pow((xy.y05 - xy.y01), 2))

        L61 = Sqrt(Pow((xy.X06 - xy.X01), 2) + Pow((xy.y06 - xy.y01), 2))

        L71 = Sqrt(Pow((xy.X07 - xy.X01), 2) + Pow((xy.y07 - xy.y01), 2))

        L81 = Sqrt(Pow((xy.X08 - xy.X01), 2) + Pow((xy.y08 - xy.y01), 2))

        L91 = Sqrt(Pow((xy.X09 - xy.X01), 2) + Pow((xy.y09 - xy.y01), 2))

        LA1 = Sqrt(Pow((xy.X0A - xy.X01), 2) + Pow((xy.y0A - xy.y01), 2))

        LB1 = Sqrt(Pow((xy.X0B - xy.X01), 2) + Pow((xy.y0B - xy.y01), 2))

        LC1 = Sqrt(Pow((xy.X0C - xy.X01), 2) + Pow((xy.y0C - xy.y01), 2))

        LD1 = Sqrt(Pow((xy.X0D - xy.X01), 2) + Pow((xy.y0D - xy.y01), 2))

        LE1 = Sqrt(Pow((xy.X0E - xy.X01), 2) + Pow((xy.y0E - xy.y01), 2))

        LF1 = Sqrt(Pow((xy.X0F - xy.X01), 2) + Pow((xy.y0F - xy.y01), 2))

        LG1 = Sqrt(Pow((xy.X0G - xy.X01), 2) + Pow((xy.y0G - xy.y01), 2))

        LH1 = Sqrt(Pow((xy.X0H - xy.X01), 2) + Pow((xy.y0H - xy.y01), 2))

        LI1 = Sqrt(Pow((xy.X0I - xy.X01), 2) + Pow((xy.y0I - xy.y01), 2))

        LJ1 = Sqrt(Pow((xy.X0J - xy.X01), 2) + Pow((xy.y0J - xy.y01), 2))

        LK1 = Sqrt(Pow((xy.X0K - xy.X01), 2) + Pow((xy.y0K - xy.y01), 2))

        LL1 = Sqrt(Pow((xy.X0L - xy.X01), 2) + Pow((xy.y0L - xy.y01), 2))

        LM1 = Sqrt(Pow((xy.X0M - xy.X01), 2) + Pow((xy.y0M - xy.y01), 2))

        LN1 = Sqrt(Pow((xy.X0N - xy.X01), 2) + Pow((xy.y0N - xy.y01), 2))

        LO1 = Sqrt(Pow((xy.X0O - xy.X01), 2) + Pow((xy.y0O - xy.y01), 2))

        LP1 = Sqrt(Pow((xy.X0P - xy.X01), 2) + Pow((xy.y0P - xy.y01), 2))

        LQ1 = Sqrt(Pow((xy.X0Q - xy.X01), 2) + Pow((xy.y0Q - xy.y01), 2))

        LR1 = Sqrt(Pow((xy.X0R - xy.X01), 2) + Pow((xy.y0R - xy.y01), 2))

        LS1 = Sqrt(Pow((xy.X0S - xy.X01), 2) + Pow((xy.y0S - xy.y01), 2))

        LT1 = Sqrt(Pow((xy.X0T - xy.X01), 2) + Pow((xy.y0T - xy.y01), 2))

        LU1 = Sqrt(Pow((xy.X0U - xy.X01), 2) + Pow((xy.y0U - xy.y01), 2))

        LV1 = Sqrt(Pow((xy.X0V - xy.X01), 2) + Pow((xy.y0V - xy.y01), 2))

        LW1 = Sqrt(Pow((xy.X0W - xy.X01), 2) + Pow((xy.y0W - xy.y01), 2))

        LX1 = Sqrt(Pow((xy.X0X - xy.X01), 2) + Pow((xy.y0X - xy.y01), 2))

        temp_returnR1 = Atan2((xy.y01 - xy.y03), (xy.X01 - xy.X03)) - Atan2(((y1 + xy.y01) - (y3 + xy.y03)), ((x1 + xy.X01) - (x3 + xy.X03)))

        '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''

        A41 = Atan2((xy.y04 - xy.y01), (xy.X04 - xy.X01)) - temp_returnR1

        A51 = Atan2((xy.y05 - xy.y01), (xy.X05 - xy.X01)) - temp_returnR1

        A61 = Atan2((xy.y06 - xy.y01), (xy.X06 - xy.X01)) - temp_returnR1

        A71 = Atan2((xy.y07 - xy.y01), (xy.X07 - xy.X01)) - temp_returnR1

        A81 = Atan2((xy.y08 - xy.y01), (xy.X08 - xy.X01)) - temp_returnR1

        A91 = Atan2((xy.y09 - xy.y01), (xy.X09 - xy.X01)) - temp_returnR1

        AA1 = Atan2((xy.y0A - xy.y01), (xy.X0A - xy.X01)) - temp_returnR1

        AB1 = Atan2((xy.y0B - xy.y01), (xy.X0B - xy.X01)) - temp_returnR1

        AC1 = Atan2((xy.y0C - xy.y01), (xy.X0C - xy.X01)) - temp_returnR1

        AD1 = Atan2((xy.y0D - xy.y01), (xy.X0D - xy.X01)) - temp_returnR1

        AE1 = Atan2((xy.y0E - xy.y01), (xy.X0E - xy.X01)) - temp_returnR1

        AF1 = Atan2((xy.y0F - xy.y01), (xy.X0F - xy.X01)) - temp_returnR1

        AG1 = Atan2((xy.y0G - xy.y01), (xy.X0G - xy.X01)) - temp_returnR1

        AH1 = Atan2((xy.y0H - xy.y01), (xy.X0H - xy.X01)) - temp_returnR1

        AI1 = Atan2((xy.y0I - xy.y01), (xy.X0I - xy.X01)) - temp_returnR1

        AJ1 = Atan2((xy.y0J - xy.y01), (xy.X0J - xy.X01)) - temp_returnR1

        AK1 = Atan2((xy.y0K - xy.y01), (xy.X0K - xy.X01)) - temp_returnR1

        AL1 = Atan2((xy.y0L - xy.y01), (xy.X0L - xy.X01)) - temp_returnR1

        AM1 = Atan2((xy.y0M - xy.y01), (xy.X0M - xy.X01)) - temp_returnR1

        AN1 = Atan2((xy.y0N - xy.y01), (xy.X0N - xy.X01)) - temp_returnR1

        AO1 = Atan2((xy.y0O - xy.y01), (xy.X0O - xy.X01)) - temp_returnR1

        AP1 = Atan2((xy.y0P - xy.y01), (xy.X0P - xy.X01)) - temp_returnR1

        AQ1 = Atan2((xy.y0Q - xy.y01), (xy.X0Q - xy.X01)) - temp_returnR1

        AR1 = Atan2((xy.y0R - xy.y01), (xy.X0R - xy.X01)) - temp_returnR1

        AS1 = Atan2((xy.y0S - xy.y01), (xy.X0S - xy.X01)) - temp_returnR1

        AT1 = Atan2((xy.y0T - xy.y01), (xy.X0T - xy.X01)) - temp_returnR1

        AU1 = Atan2((xy.y0U - xy.y01), (xy.X0U - xy.X01)) - temp_returnR1

        AV1 = Atan2((xy.y0V - xy.y01), (xy.X0V - xy.X01)) - temp_returnR1

        AW1 = Atan2((xy.y0W - xy.y01), (xy.X0W - xy.X01)) - temp_returnR1

        AX1 = Atan2((xy.y0X - xy.y01), (xy.X0X - xy.X01)) - temp_returnR1
        ''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''

        temp_returnX1 = x1 + xy.X01 - xy.X04 + L41 * Cos(A41)

        temp_returnY1 = y1 + xy.y01 - xy.y04 + L41 * Sin(A41)

        returnxy.X1 = temp_returnX1
        returnxy.Y1 = temp_returnY1

        temp_returnX1 = x1 + xy.X01 - xy.X05 + L51 * Cos(A51)

        temp_returnY1 = y1 + xy.y01 - xy.y05 + L51 * Sin(A51)

        returnxy.X2 = temp_returnX1
        returnxy.Y2 = temp_returnY1

        temp_returnX1 = x1 + xy.X01 - xy.X06 + L61 * Cos(A61)

        temp_returnY1 = y1 + xy.y01 - xy.y06 + L61 * Sin(A61)

        returnxy.X3 = temp_returnX1
        returnxy.Y3 = temp_returnY1

        temp_returnX1 = x1 + xy.X01 - xy.X07 + L71 * Cos(A71)

        temp_returnY1 = y1 + xy.y01 - xy.y07 + L71 * Sin(A71)

        returnxy.X4 = temp_returnX1
        returnxy.Y4 = temp_returnY1

        temp_returnX1 = x1 + xy.X01 - xy.X08 + L81 * Cos(A81)

        temp_returnY1 = y1 + xy.y01 - xy.y08 + L81 * Sin(A81)

        returnxy.X5 = temp_returnX1
        returnxy.Y5 = temp_returnY1

        temp_returnX1 = x1 + xy.X01 - xy.X09 + L91 * Cos(A91)

        temp_returnY1 = y1 + xy.y01 - xy.y09 + L91 * Sin(A91)

        returnxy.X6 = temp_returnX1
        returnxy.Y6 = temp_returnY1

        temp_returnX1 = x1 + xy.X01 - xy.X0A + LA1 * Cos(AA1)

        temp_returnY1 = y1 + xy.y01 - xy.y0A + LA1 * Sin(AA1)

        returnxy.X7 = temp_returnX1
        returnxy.Y7 = temp_returnY1

        temp_returnX1 = x1 + xy.X01 - xy.X0B + LB1 * Cos(AB1)

        temp_returnY1 = y1 + xy.y01 - xy.y0B + LB1 * Sin(AB1)

        returnxy.X8 = temp_returnX1
        returnxy.Y8 = temp_returnY1

        temp_returnX1 = x1 + xy.X01 - xy.X0C + LC1 * Cos(AC1)

        temp_returnY1 = y1 + xy.y01 - xy.y0C + LC1 * Sin(AC1)

        returnxy.X9 = temp_returnX1
        returnxy.Y9 = temp_returnY1

        temp_returnX1 = x1 + xy.X01 - xy.X0D + LD1 * Cos(AD1)

        temp_returnY1 = y1 + xy.y01 - xy.y0D + LD1 * Sin(AD1)

        returnxy.X10 = temp_returnX1
        returnxy.Y10 = temp_returnY1

        temp_returnX1 = x1 + xy.X01 - xy.X0E + LE1 * Cos(AE1)

        temp_returnY1 = y1 + xy.y01 - xy.y0E + LE1 * Sin(AE1)

        returnxy.X11 = temp_returnX1
        returnxy.Y11 = temp_returnY1

        temp_returnX1 = x1 + xy.X01 - xy.X0F + LF1 * Cos(AF1)

        temp_returnY1 = y1 + xy.y01 - xy.y0F + LF1 * Sin(AF1)

        returnxy.X12 = temp_returnX1
        returnxy.Y12 = temp_returnY1

        temp_returnX1 = x1 + xy.X01 - xy.X0G + LG1 * Cos(AG1)

        temp_returnY1 = y1 + xy.y01 - xy.y0G + LG1 * Sin(AG1)

        returnxy.X13 = temp_returnX1
        returnxy.Y13 = temp_returnY1

        temp_returnX1 = x1 + xy.X01 - xy.X0H + LH1 * Cos(AH1)

        temp_returnY1 = y1 + xy.y01 - xy.y0H + LH1 * Sin(AH1)

        returnxy.X14 = temp_returnX1
        returnxy.Y14 = temp_returnY1

        temp_returnX1 = x1 + xy.X01 - xy.X0I + LI1 * Cos(AI1)

        temp_returnY1 = y1 + xy.y01 - xy.y0I + LI1 * Sin(AI1)

        returnxy.X15 = temp_returnX1
        returnxy.Y15 = temp_returnY1

        temp_returnX1 = x1 + xy.X01 - xy.X0J + LJ1 * Cos(AJ1)

        temp_returnY1 = y1 + xy.y01 - xy.y0J + LJ1 * Sin(AJ1)

        returnxy.X16 = temp_returnX1
        returnxy.Y16 = temp_returnY1

        temp_returnX1 = x1 + xy.X01 - xy.X0K + LK1 * Cos(AK1)

        temp_returnY1 = y1 + xy.y01 - xy.y0K + LK1 * Sin(AK1)

        returnxy.X17 = temp_returnX1
        returnxy.Y17 = temp_returnY1

        temp_returnX1 = x1 + xy.X01 - xy.X0L + LL1 * Cos(AL1)

        temp_returnY1 = y1 + xy.y01 - xy.y0L + LL1 * Sin(AL1)

        returnxy.X18 = temp_returnX1
        returnxy.Y18 = temp_returnY1

        temp_returnX1 = x1 + xy.X01 - xy.X0M + LM1 * Cos(AM1)

        temp_returnY1 = y1 + xy.y01 - xy.y0M + LM1 * Sin(AM1)

        returnxy.X19 = temp_returnX1
        returnxy.Y19 = temp_returnY1

        temp_returnX1 = x1 + xy.X01 - xy.X0N + LN1 * Cos(AN1)

        temp_returnY1 = y1 + xy.y01 - xy.y0N + LN1 * Sin(AN1)

        returnxy.X20 = temp_returnX1
        returnxy.Y20 = temp_returnY1

        temp_returnX1 = x1 + xy.X01 - xy.X0O + LO1 * Cos(AO1)

        temp_returnY1 = y1 + xy.y01 - xy.y0O + LO1 * Sin(AO1)

        returnxy.X21 = temp_returnX1
        returnxy.Y21 = temp_returnY1

        temp_returnX1 = x1 + xy.X01 - xy.X0P + LP1 * Cos(AP1)

        temp_returnY1 = y1 + xy.y01 - xy.y0P + LP1 * Sin(AP1)

        returnxy.X22 = temp_returnX1
        returnxy.Y22 = temp_returnY1

        temp_returnX1 = x1 + xy.X01 - xy.X0Q + LQ1 * Cos(AQ1)

        temp_returnY1 = y1 + xy.y01 - xy.y0Q + LQ1 * Sin(AQ1)

        returnxy.X23 = temp_returnX1
        returnxy.Y23 = temp_returnY1

        temp_returnX1 = x1 + xy.X01 - xy.X0R + LR1 * Cos(AR1)

        temp_returnY1 = y1 + xy.y01 - xy.y0R + LR1 * Sin(AR1)

        returnxy.X24 = temp_returnX1
        returnxy.Y24 = temp_returnY1

        temp_returnX1 = x1 + xy.X01 - xy.X0S + LS1 * Cos(AS1)

        temp_returnY1 = y1 + xy.y01 - xy.y0S + LS1 * Sin(AS1)

        returnxy.X25 = temp_returnX1
        returnxy.Y25 = temp_returnY1

        temp_returnX1 = x1 + xy.X01 - xy.X0T + LT1 * Cos(AT1)

        temp_returnY1 = y1 + xy.y01 - xy.y0T + LT1 * Sin(AT1)

        returnxy.X26 = temp_returnX1
        returnxy.Y26 = temp_returnY1

        temp_returnX1 = x1 + xy.X01 - xy.X0U + LU1 * Cos(AU1)

        temp_returnY1 = y1 + xy.y01 - xy.y0U + LU1 * Sin(AU1)

        returnxy.X27 = temp_returnX1
        returnxy.Y27 = temp_returnY1

        temp_returnX1 = x1 + xy.X01 - xy.X0V + LV1 * Cos(AV1)
        temp_returnY1 = y1 + xy.y01 - xy.y0V + LV1 * Sin(AV1)

        returnxy.X28 = temp_returnX1
        returnxy.Y28 = temp_returnY1

        temp_returnX1 = x1 + xy.X01 - xy.X0W + LW1 * Cos(AW1)
        temp_returnY1 = y1 + xy.y01 - xy.y0W + LW1 * Sin(AW1)

        returnxy.X29 = temp_returnX1
        returnxy.Y29 = temp_returnY1

        temp_returnX1 = x1 + xy.X01 - xy.X0X + LX1 * Cos(AX1)

        temp_returnY1 = y1 + xy.y01 - xy.y0X + LX1 * Sin(AX1)

        returnxy.X30 = temp_returnX1
        returnxy.Y30 = temp_returnY1
eend:

        For q = 0 To 59
            resu(q) = returnxy.read()(q)
        Next
        bzw = 0
over:
        Return returnxy

    End Function

    Sub InitSetting()
        Try

            Dim filepath = DebugPath & "\Tool\"
            Dim OpenPsetsetting As Boolean = Exists(filepath & TCmbPro.Text & "\Psetsetting.txt")
            Dim openhistroy As Boolean = Exists(DebugPath & "\log" & "\" & "System_Histroy_" & Format(Date.Now.Date, "yyyyMMdd") & ".txt")
            Dim openSet As Boolean = Exists(filepath & "\Set.txt")
            Dim openGet As Boolean = Exists(filepath & "\Get.txt")
            Dim Alarmsetting As Boolean = Exists(filepath & "Alarmsetting.txt")
            Dim Access As Boolean = Exists(filepath & "\Robot_Or_Access.txt")
            Dim openParameter As Boolean = Exists(filepath & TCmbPro.Text & "\Parameter.txt")

            Dim SNSET As Boolean = Exists(filepath & "\SNdate.txt")
            Dim JQSN As Boolean = Exists(filepath & "\JQGZ.txt")
            Dim PsetCompensate As PsetSetting
            Dim newset1 As Boolean
            Dim Alarmsettinginfo As AlarmSetting

            If openhistroy = False Then
                SaveSetting("XCPro", "Settings", "UserTimes", gUserTime - 1)
                Dim fileNum As Integer
                fileNum = FreeFile()
                FileOpen(fileNum, DebugPath & "\log" & "\" & "System_Histroy_" & Format(Date.Now.Date, "yyyyMMdd") & ".txt", OpenMode.Append)
                FileClose(fileNum)
            End If
            FileClose(file_num_count)
            If Directory.Exists(filepath & "\") = False Then  '判断文件夹是否存在
                Directory.CreateDirectory(filepath & "\")
            End If

            FileOpen(file_num_count, filepath & "\count.txt", OpenMode.Random)
            Do While Not EOF(file_num_count)
                FileGet(file_num_count, Todaycount)
            Loop
            FileClose(file_num_count)

            FileOpen(file_num_count1, filepath & "\count1.txt", OpenMode.Random)
            Do While Not EOF(file_num_count1)
                FileGet(file_num_count1, Todaycount1)
            Loop
            FileClose(file_num_count1)

            FileOpen(file_num_count3, filepath & "\count3.txt", OpenMode.Random)
            Do While Not EOF(file_num_count3)
                FileGet(file_num_count1, Todaycount3)
            Loop
            FileClose(file_num_count3)

            FileOpen(file_num_count4, filepath & "\count4.txt", OpenMode.Random)
            Do While Not EOF(file_num_count4)
                FileGet(file_num_count1, Todaycount4)
            Loop
            FileClose(file_num_count4)

            TextBox6.Text = Todaycount.Screwcount.ToString
            TextBox1.Text = Todaycount.PassCount.ToString
            TextBox2.Text = Todaycount.NGCount.ToString
            TextBox3.Text = Todaycount.SCount.ToString
            ScrewFailed1.Text = Todaycount.ScrewFailed1
            ScrewFailed2.Text = Todaycount.ScrewFailed2
            ScrewFailed3.Text = Todaycount.ScrewFailed3
            ScrewFailed4.Text = Todaycount.ScrewFailed4
            ScrewFailed5.Text = Todaycount.ScrewFailed5
            ScrewFailed6.Text = Todaycount.ScrewFailed6
            ScrewFailed7.Text = Todaycount.ScrewFailed7
            ScrewFailed8.Text = Todaycount.ScrewFailed8
            ScrewFailed9.Text = Todaycount.ScrewFailed9
            ScrewFailed10.Text = Todaycount.ScrewFailed10
            ScrewFailed11.Text = Todaycount.ScrewFailed11
            ScrewFailed12.Text = Todaycount.ScrewFailed12
            ScrewFailed13.Text = Todaycount.ScrewFailed13
            ScrewFailed14.Text = Todaycount.ScrewFailed14
            ScrewFailed15.Text = Todaycount1.ScrewFailed15
            ScrewFailed16.Text = Todaycount1.ScrewFailed16
            ScrewFailed17.Text = Todaycount1.ScrewFailed17
            ScrewFailed18.Text = Todaycount1.ScrewFailed18
            ScrewFailed19.Text = Todaycount1.ScrewFailed19
            ScrewFailed20.Text = Todaycount1.ScrewFailed20
            ScrewFailed21.Text = Todaycount1.ScrewFailed21
            ScrewFailed22.Text = Todaycount1.ScrewFailed22
            ScrewFailed23.Text = Todaycount1.ScrewFailed23
            ScrewFailed24.Text = Todaycount1.ScrewFailed24
            ScrewFailed25.Text = Todaycount1.ScrewFailed25
            ScrewFailed26.Text = Todaycount1.ScrewFailed26
            ScrewFailed27.Text = Todaycount1.ScrewFailed27
            ScrewFailed28.Text = Todaycount1.ScrewFailed28
            ScrewFailed29.Text = Todaycount1.ScrewFailed29
            ScrewFailed30.Text = Todaycount1.ScrewFailed30
            '异常管理
            'ScrewFailed_1.Text = Todaycount.ScrewFailed1
            'ScrewFailed_2.Text = Todaycount.ScrewFailed2
            'ScrewFailed_3.Text = Todaycount.ScrewFailed3
            'ScrewFailed_4.Text = Todaycount.ScrewFailed4
            'ScrewFailed_5.Text = Todaycount.ScrewFailed5
            'ScrewFailed_6.Text = Todaycount.ScrewFailed6
            'ScrewFailed_7.Text = Todaycount.ScrewFailed7
            'ScrewFailed_8.Text = Todaycount.ScrewFailed8
            'ScrewFailed_9.Text = Todaycount.ScrewFailed9
            'ScrewFailed_10.Text = Todaycount.ScrewFailed10
            'ScrewFailed_11.Text = Todaycount.ScrewFailed11
            'ScrewFailed_12.Text = Todaycount.ScrewFailed12
            'ScrewFailed_13.Text = Todaycount.ScrewFailed13
            'ScrewFailed_14.Text = Todaycount.ScrewFailed14
            'ScrewFailed_15.Text = Todaycount1.ScrewFailed15
            'ScrewFailed_16.Text = Todaycount1.ScrewFailed16
            'ScrewFailed_17.Text = Todaycount1.ScrewFailed17
            'ScrewFailed_18.Text = Todaycount1.ScrewFailed18
            'ScrewFailed_19.Text = Todaycount1.ScrewFailed19
            'ScrewFailed_20.Text = Todaycount1.ScrewFailed20
            'ScrewFailed_21.Text = Todaycount1.ScrewFailed21
            'ScrewFailed_22.Text = Todaycount1.ScrewFailed22
            'ScrewFailed_23.Text = Todaycount1.ScrewFailed23
            'ScrewFailed_24.Text = Todaycount1.ScrewFailed24
            'ScrewFailed_25.Text = Todaycount1.ScrewFailed25
            'ScrewFailed_26.Text = Todaycount1.ScrewFailed26
            'ScrewFailed_27.Text = Todaycount1.ScrewFailed27
            'ScrewFailed_28.Text = Todaycount1.ScrewFailed28
            'ScrewFailed_29.Text = Todaycount1.ScrewFailed29
            'ScrewFailed_30.Text = Todaycount1.ScrewFailed30
            SkipFailed1.Text = Todaycount3.SkipFailed1
            SkipFailed2.Text = Todaycount3.SkipFailed2
            SkipFailed3.Text = Todaycount3.SkipFailed3
            SkipFailed4.Text = Todaycount3.SkipFailed4
            SkipFailed5.Text = Todaycount3.SkipFailed5
            SkipFailed6.Text = Todaycount3.SkipFailed6
            SkipFailed7.Text = Todaycount3.SkipFailed7
            SkipFailed8.Text = Todaycount3.SkipFailed8
            SkipFailed9.Text = Todaycount3.SkipFailed9
            SkipFailed10.Text = Todaycount3.SkipFailed10
            SkipFailed11.Text = Todaycount3.SkipFailed11
            SkipFailed12.Text = Todaycount3.SkipFailed12
            SkipFailed13.Text = Todaycount3.SkipFailed13
            SkipFailed14.Text = Todaycount3.SkipFailed14
            SkipFailed15.Text = Todaycount4.SkipFailed15
            SkipFailed16.Text = Todaycount4.SkipFailed16
            SkipFailed17.Text = Todaycount4.SkipFailed17
            SkipFailed18.Text = Todaycount4.SkipFailed18
            SkipFailed19.Text = Todaycount4.SkipFailed19
            SkipFailed20.Text = Todaycount4.SkipFailed20
            SkipFailed21.Text = Todaycount4.SkipFailed21
            SkipFailed22.Text = Todaycount4.SkipFailed22
            SkipFailed23.Text = Todaycount4.SkipFailed23
            SkipFailed24.Text = Todaycount4.SkipFailed24
            SkipFailed25.Text = Todaycount4.SkipFailed25
            SkipFailed26.Text = Todaycount4.SkipFailed26
            SkipFailed27.Text = Todaycount4.SkipFailed27
            SkipFailed28.Text = Todaycount4.SkipFailed28
            SkipFailed29.Text = Todaycount4.SkipFailed29
            SkipFailed30.Text = Todaycount4.SkipFailed30
            SFTime.Text = Format(Todaycount.SFTime, "0.0")
            IDELTime.Text = Format(Todaycount.IDELTime, "0.0")
            SDTime.Text = Format(Todaycount.ShutDownTime, "0.0")
            bzw = 0
            If TextBox1.Text = "0" Or TextBox6.Text = "0" Then
                TextBox7.Text = "100.00%"
                mainInfo.Yield = TextBox7.Text
            Else
                Dim NGFG As Integer = Val(TextBox3.Text) + Val(TextBox14.Text)
                Dim ng As Double = 100 * (1 - Val(NGFG) / Val(TextBox6.Text))
                TextBox7.Text = Format(ng, "0.00") & "%"
                mainInfo.Yield = TextBox7.Text
            End If
            ' 加载异常台数机、cycle time
            FileOpen(file_num_count2, filepath & "\count2.txt", OpenMode.Random)
            Do While Not EOF(file_num_count2)
                FileGet(file_num_count2, Todaycount2)
            Loop
            FileClose(file_num_count2)

            TextBox_PCSFailed.Text = Todaycount2.PCSFailed
            TextBox5.Text = Todaycount2.SuctionCount
            TextBox14.Text = Todaycount2.Height_float
            TextBox_CT.Text = Todaycount2.CycleTime
            If TextBox1.Text = "0" Then
                TextBox_Yield.Text = "100.00%"
            Else
                Dim ng As Double = 100 * (1 - Val(TextBox_PCSFailed.Text) / Val(TextBox1.Text))
                TextBox_Yield.Text = Format(ng, "0.00") & "%"
            End If

            '加载螺丝参数
            If openParameter = True Then
                Dim file_num As Integer = FreeFile()
                FileOpen(file_num, filepath & TCmbPro.Text & "\Parameter.txt", OpenMode.Random)
                FileGet(file_num, CurScrewPara)
                TextBox_CurScrewSN.Text = CurScrewPara.ScrewSN
                SNInfo.Screw_Qty = CurScrewPara.PointCount
                FileClose(file_num)
            Else
                CurScrewPara.PointCount = 0
                CurScrewPara.FloatMin = 0
                CurScrewPara.FloatMax = 0
                AppendInfoToTextBox("未设置螺丝颗数!")
            End If
            'WriteDeviceRandom_Torsion("D254", Val(CurScrewPara.FloatMin) * 10) '写入最小浮高
            'WriteDeviceRandom_Torsion("D254", Val(CurScrewPara.FloatMax) * 10) '写入最大浮高
            '加载设置参数
            If OpenPsetsetting = True Then
                Dim file_num As Integer = FreeFile()
                FileOpen(file_num, filepath & TCmbPro.Text & "\Psetsetting.txt", OpenMode.Random)
                Dim j As Integer = 0

                Do While Not EOF(file_num)
                    FileGet(file_num, PsetCompensate)
                    Pset(j) = PsetCompensate

                    j += 1
                Loop
                NumberOfPSetArray = j
                FileClose(file_num)
            Else
                For i As Integer = 0 To NumberOfPSetArray - 1
                    Pset(i).XPosCompensate = 0
                    Pset(i).YPosCompensate = 0
                    Pset(i).ZPosCompensate = 0
                Next
            End If

            If Alarmsetting = True Then
                Dim file_num As Integer = FreeFile()
                FileOpen(file_num, filepath & "alarmsetting.txt", OpenMode.Random, OpenAccess.Default, OpenShare.Default, 1000)
                Dim j As Integer = 0
                Do While Not EOF(file_num)
                    FileGet(file_num, Alarmsettinginfo)
                    myalarm(j) = Alarmsettinginfo
                    j += 1
                Loop
                NumberOfAlarmArray = j
                FileClose(file_num)
            Else
                For i = 0 To NumberOfAlarmArray - 1
                    myalarm(i).AlarmID = 0
                    myalarm(i).AlarmInfo = ""
                    myalarm(i).Alarmprocess = ""
                Next

            End If

            If openSet = True Then
                Dim file_num As Integer = FreeFile()
                FileOpen(file_num, filepath & "\Set.txt", OpenMode.Random)
                Dim j As Integer = 0
                Do While Not EOF(file_num)
                    FileGet(file_num, newset1)
                    newset(j) = newset1
                    j += 1
                Loop
                NumberOfSet = j
                FileClose(file_num)
            Else
                For i As Integer = 0 To 6
                    newset(i) = False
                Next
            End If
            '''''''''''''''增加SN扫码方式
            'If SNSET = True Then
            '    Dim file_num As Integer = FreeFile()
            '    FileOpen(file_num, filepath & "\SNdate.txt", OpenMode.Random)
            '    FileGet(file_num, SN_CheckMode)
            '    FileClose(file_num)
            'Else
            '    SN_CheckMode = 0
            'End If
            ''''''''''''''''''''''''''
            If openGet = True Then
                Dim file_num As Integer = FreeFile()
                FileOpen(file_num, filepath & "\Get.txt", OpenMode.Random)
                Dim j As Integer = 0
                Do While Not EOF(file_num)
                    FileGet(file_num, PsetCompensate)
                    Pget(j) = PsetCompensate
                    j += 1
                Loop
                ADD_Screw_Count = Pget(3).XPosCompensate
                Retry_Times = Pget(3).YPosCompensate
                Clear_Time = Pget(3).ZPosCompensate
                NumberOfGet = j
                FileClose(file_num)
            Else
                For i As Integer = 0 To NumberOfGet - 1
                    Pget(i).XPosCompensate = 0
                    Pget(i).YPosCompensate = 0
                    Pget(i).ZPosCompensate = 0
                Next
                Pget(2).XPosCompensate = -1
                Pget(2).YPosCompensate = 1
                Pget(2).ZPosCompensate = 0.5
                Pget(3).XPosCompensate = 120
                Pget(3).YPosCompensate = 2
                Pget(3).ZPosCompensate = 8

                ADD_Screw_Count = Pget(3).XPosCompensate
                Retry_Times = Pget(3).YPosCompensate
                Clear_Time = Pget(3).ZPosCompensate
            End If
            '获取第三拍拍照点数据,以及联机方式，锁付模式
            Dim openPhoto3date As Boolean = Exists(DebugPath & "\Tool\Photo3.txt")
            If openPhoto3date = True Then
                Dim startDly As Integer = FreeFile()
                FileOpen(startDly, DebugPath & "\Tool\Photo3.txt", OpenMode.Random)
                FileGet(startDly, Photo3_flag)
                FileGet(startDly, KESU)
                FileGet(startDly, Online_Mod)
                FileGet(startDly, suofu_Mod)
                FileGet(startDly, SN2Check)
                FileGet(startDly, Y轴_最小偏差限制)
                FileGet(startDly, Y轴_最大偏差限制)
                FileClose(startDly)
            Else
                Photo3_flag = False
                KESU = 4
                Online_Mod = 1
                suofu_Mod = 1
                SN2Check = False
                Y轴_最小偏差限制 = -15
                Y轴_最大偏差限制 = 15
            End If

            Dim openPhoto As Boolean = Exists(DebugPath & "\Tool\" & TCmbPro.Text & "\Photo-PH.txt")
            If openPhoto = True Then
                Dim startDly1 As Integer = FreeFile()
                FileOpen(startDly1, DebugPath & "\Tool\" & TCmbPro.Text & "\Photo-PH.txt", OpenMode.Random)
                FileGet(startDly1, PhotoPY_flag)
                FileGet(startDly1, PhotoPY)

                FileClose(startDly1)
            Else
                PhotoPY_flag = True
                PhotoPY = 0

            End If

            '获取斜锁路锁付方式
            GetPointWay()

            '获取Z相检测设定值
            Dim Zcheckpls_num As Integer = FreeFile()
            Dim OpenZpls As Boolean = Exists(filepath & TCmbPro.Text & "\ZaxisCheck.txt")
            Dim s As String = ""
            Dim ss() As String

            If OpenZpls = True Then
                FileOpen(Zcheckpls_num, filepath & TCmbPro.Text & "\ZaxisCheck.txt", OpenMode.Random)
                FileGet(Zcheckpls_num, s)
                ss = Split(s, ",")
                For i = 0 To 30
                    ZaxisPls(i) = Val(ss(i))
                Next
                ZaxisCheckUSE = ss(31)
                FileClose(Zcheckpls_num)
            Else
                For i = 0 To 30
                    ZaxisPls(i) = 0
                Next
                ZaxisCheckUSE = False
            End If

            If JQSN Then
                Dim startDly1 As Integer = FreeFile()
                FileOpen(startDly1, filepath & "\JQGZ.txt", OpenMode.Random)
                FileGet(startDly1, JQStart)
                FileGet(startDly1, JQLength)
                FileClose(startDly1)
            End If
            '获取打螺丝参数
            GetPointPara()
            '初始化设备信息
            'InitMachineInfo()
            If newset(7) Then
                TextBox8_UpLoadStatus.BackColor = Color.Lime
                TextBox8_UpLoadStatus.Text = "开启"
            Else
                TextBox8_UpLoadStatus.BackColor = Color.Red
                TextBox8_UpLoadStatus.Text = "关闭"
            End If
        Catch ex As Exception
            AppendInfoToTextBox("InitSetting:" & ex.Message.ToString)
        End Try
    End Sub

    Private Sub GetDirectFiles(ByVal s As String)
        '找出位于 s 根目录下的所有文件
        Dim f() As String
        Try
            Dim i As Integer
            Dim t As Collections.ObjectModel.ReadOnlyCollection(Of String) = My.Computer.FileSystem.GetFiles(s), k As String, name() As String
            ' Me.Text = s
            Me.TCmbPro.Items.Clear()
            For Each k In My.Computer.FileSystem.GetDirectories(s)
                ReDim Preserve f(i)
                f(i) = k
                If 1 Then

                    Dim myFileInfo As New IO.FileInfo(f(i))
                    name = Split(f(i), "\")
                    ' f(i) = Right(f(i), f(i).Length - name.Length)
                    'C1FlexGrid1.Item(i + 1, 2) = name(UBound(name)) '获取文件名
                    'C1FlexGrid1.Item(i + 1, 3) = myFileInfo.LastWriteTime '获取文件名
                    Me.TCmbPro.Items.Add(name(name.Length - 1))
                End If
                i += 1
            Next
            TCmbPro.SelectedItem = gCurrProName
        Catch
        End Try
    End Sub

    Private Declare Function SetParent Lib "user32.dll" (
                ByVal hWndChild As Long,
                ByVal hWndNewParent As Long) As Long

    Private Declare Function SetWindowLong Lib "user32.dll" Alias "SetWindowLongA" (
              ByVal hwnd As Long,
              ByVal nIndex As Long,
              ByVal dwNewLong As Long) As Long
    Private Declare Function SetParent Lib "user32" Alias "SetParent" (ByVal hWndChild As IntPtr, ByVal hWndNewParent As IntPtr) As Integer
    Private Declare Function FindWindow Lib "user32" Alias "FindWindowA" (ByVal lpClassName As String, ByVal lpWindowName As String) As IntPtr
    Private Declare Function MoveWindow Lib "user32" (ByVal hwnd As Integer, ByVal x As Integer, ByVal y As Integer, ByVal nWidth As Integer, ByVal nHeight As Integer, ByVal bRepaint As Integer) As Integer
    Private Declare Function SetCursorPos Lib "User32" (ByVal x As Integer, ByVal y As Integer) As Boolean
    Declare Function SendMessage Lib "user32" Alias "SendMessageA" (ByVal hwnd As IntPtr, ByVal wMsg As IntPtr, ByVal wParam As IntPtr, ByVal lParam As String) As IntPtr
    Declare Function FindWindowEx Lib "user32" Alias "FindWindowExA" (ByVal hWnd1 As IntPtr, ByVal hWnd2 As IntPtr, ByVal lpsz1 As String, ByVal lpsz2 As String) As IntPtr
    Declare Function PostMessage Lib "user32" Alias "PostMessageA" (ByVal hwnd As IntPtr, ByVal wMsg As IntPtr, ByVal wParam As IntPtr, ByVal lParam As String) As IntPtr

    Private Declare Sub mouse_event Lib "user32" (ByVal dwFlags As Integer, ByVal dx As Integer, ByVal dy As Integer, ByVal cButtons As Integer, ByVal dwExtraInfo As Integer)
    Private Const MOUSEEVENTF_LEFTDOWN = &H2
    Private Const MOUSEEVENTF_LEFTUP = &H4
    Public Const WM_CLOSE = &H10

    Dim exeName As String = "C:\Program Files (x86)\PM Designer\V2.1\PanelSim.exe"

    Private Sub FrmMain_KeyUp(sender As Object, e As KeyEventArgs) Handles Me.KeyUp

    End Sub

    Private Sub FrmMain_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Me.Visible = False
        'DataByReal.Status = "On"
        TabControl1.SelectedIndex = 2
        'TabControl1.TabPages.Remove(TabControl1.TabPages(TabControl1.TabPages.Count - 1)) '隐藏锁附点显示
        'TabControl1.TabPages.Remove(TabControl1.TabPages(TabControl1.TabPages.Count - 1)) '隐藏异常管理
        '启动触摸屏程序
        Dim frm As New NCHQMES.FrmMesMachineInfo
        frm.ShowDialog()
        ' Method.RichTextBox_Mes = RichTextBox_Mes
        Dim appwin As IntPtr
        Dim Process As Process
        Try
            Process = System.Diagnostics.Process.Start(exeName)
            Process.WaitForInputIdle()
            appwin = Process.MainWindowHandle
            System.Threading.Thread.Sleep(100)
        Catch ex As Exception
            MessageBox.Show(Me, ex.Message, "Error")
        End Try
        SetParent(appwin, Me.Panel1.Handle)
        MoveWindow(appwin, 0, 0, Me.Width, Me.Height, True)

        Control.CheckForIllegalCrossThreadCalls = False
        Me.FormBorderStyle = Windows.Forms.FormBorderStyle.None
        Me.WindowState = FormWindowState.Maximized
        '  frmShowAlarm.ShowDialog()
        Dim createdNew As Boolean
        Dim mutex As System.Threading.Mutex = New System.Threading.Mutex(True, "YourAppName", createdNew)
        If createdNew = False Then
            MessageBox.Show("已经一个实例的本程序正在运行。")
            End

        End If

        'Application.Run(New Form())        ' 释放mutex
        mutex.ReleaseMutex()

        GetXML()

        '初始化加密狗
        'initkey()

        '初始化参数
        initParam()
        Me.Show()
        ' SetCursorPos(580, 280)
        SetCursorPos(670, 300)
        mouse_event(&H2, 0, 0, 0, 0) '鼠标左键按下

        mouse_event(&H4, 0, 0, 0, 0) '鼠标左键弹起

        '初始化IO
        'InitIO()

        '初始化通讯
        InitCom()

        '初始化设备信息
        InitMachineInfo()
        ''开启上传程序()
        ''OpenUploadProcess()
        '功能启用
        ParameterSet.GetEnableFlag()

        '初始化锁附模板
        'If ResultShow_flag = True Then
        '    initPointModel(Chanpin)
        'End If

        'If Access_enable Then
        '    LoadAccess()
        'End If
        '初始化网口
        InitTcpSever()
        'socket2 = New SocketHelper()
        IPAddm(0) = "192.168.2.100"
        IPAddm(1) = "192.168.2.101"
        IPAddm(2) = "192.168.2.102"
        IPAddm(3) = "192.168.2.103"
        IPAddm(4) = "192.168.2.104"
        IPAddm(5) = "192.168.2.105"
        'InitTcpSever2()
        'InitTcpSever()

        '开机延时
        'StartDly()

        '连接PLC
        'Open_Click_PLC()
        If PLC_brands = "西门子_200_smart" Then
            SIEMENS_PLC_Communications_link()
        ElseIf PLC_brands = "三菱_FX5U" Then
            'Open_Click_PLC()
            Sanlin_PLC_Communications_link()
        End If

        '如果有默认产品，则初始化产品参数
        If gCurrProName <> "" Then
            '初始化已设定好的工具
            initPro(gCurrProName)
        Else
            '初始化图像处理工具
            initTool()
        End If

        '初始化设置
        InitSetting()
        '初始化完成后，权限管理启用
        gPriority = 0
        TimerLight.Enabled = True
        TextBox_OPID.Text = "未登陆"
        FrmAdmin.EnableMenu()
        initOK_flag = True
        '确认路径
        CheckVisionfailedPath()
        '删除过期图片\上传数据
        DeleteDir(gVisionFailedPath)
        UploadStatus.Enabled = True
        UploadMainInfo.Enabled = True
        machineInfoStatus.Status = "3" 'XCPro开机
        machineInfoStatus.ErrorCode = ""
        SNInfo.Family = TCmbPro.Text
        'uploadstate()

        Timer3.Enabled = True
        'ConnectRobot()
        Me.Visible = True
        Timer_SMSB.Enabled = True
        Timer_DL.Enabled = True
        Timer_QZCS.Enabled = True

        If newset(7) Then
            Try
                AppendMESToTextBox(Method.MES_SCADA_Startup(TextBox_OPID.Text))
            Catch ex As Exception
                AddErrMsgToTextBox(ex.Message)
                MesConectFlag = False
            End Try

        End If
        Try
            Method.DeletePath(DebugPath & "\log")
            Method.DeletePath(DebugPath & "\Err_log")
            Method.DeletePath(DebugPath & "\MesLog")
        Catch ex As Exception
            AddErrMsgToTextBox("删除文件错误,错误信息{" & ex.Message.ToString() & "}")
        End Try
    End Sub

    Public strNum As String    'xjh
    Public uPianCha(7) As Double  '= {0.0, 0.0, 0.0, 7.46, 8.186, 9.551, 9.551, 12.439}
    Public dPianCha(7) As Double  '= {0.0, 0.0, 0.0, 7.916, 5.71, 8.775, 9.714, 11.616}

    '    Public Const umpi As Double = 1.0
    Dim ulimit, dlimit As Double

    Dim udlimit As Double

    Private Sub SP1_DataReceived(ByVal sender As Object, ByVal e As System.IO.Ports.SerialDataReceivedEventArgs) Handles SP1.DataReceived '串口数据获取

        Try
            'invoke申明
            If InvokeRequired Then
                Dim eventArgs() As Object = {sender, e}
                Invoke(New EventHandler(AddressOf SP1_DataReceived), eventArgs)
                Return
            End If

            '读取数据
            wait(50)
            Dim byteToRead As Int16
            byteToRead = SP1.BytesToRead
            AppendInfoToTextBox("byteToRead:" & SP1.BytesToRead)
            Dim ch(byteToRead) As Byte
            Dim bytesRead As Int16 = 0
            bytesRead = SP1.Read(ch, 0, byteToRead)
            Dim indata As String = ""
            SPString = ""
            For i As Int16 = 0 To bytesRead - 1
                ReceiveModbus(i) = ch(i)
                SPString = SPString & Chr(ch(i))
                'indata = indata & DecToHex(ch(i))
            Next
            Dim sna As String = SPString.Split(vbCrLf)(0)
            If sna.StartsWith(JQStart) And sna.Length >= JQLength Then
                Dim str As StringBuilder = New StringBuilder()
                For a As Integer = 0 To JQLength - 1
                    str.Append(sna(a))
                Next

                Try
                    Dim sn As String = str.ToString()
                    SNInputBox.Text = sn
                    ScanSNAndMESRequest(sn)
                Catch ex As Exception
                    AddErrMsgToTextBox("访问MES出错")
                End Try
            End If

            'REPLY_MES = SPString
            'SN_Queue.Enqueue(REPLY_MES)
            'showSNQueueFlag = True
        Catch ex As Exception
            WriteInspecLog(TSLog, "COMRecvErr" & vbTab & ex.Message) '错误信息写入log
        End Try
    End Sub

    '图像处理
    'Private Sub imageProcessing()
    '    Dim cur_cam_num As Integer = 0
    '    Dim tmpfifo As CogAcqFifoTool
    '    Dim c1, c2, score1, score2 As Double
    '    Dim scorelimit As Double = 0.79
    '    gTotalNum += 1  '无关紧要
    '    '开始检测
    '    cur_cam_num = 0   '　处理第一个相机设定
    '    gTotalNumCam(cur_cam_num) += 1
    '    uPianCha(0) = gTBCheck(1).Inputs.Item("u0").Value()
    '    dPianCha(0) = gTBCheck(1).Inputs.Item("d0").Value()
    '    uPianCha(1) = gTBCheck(1).Inputs.Item("u1").Value()
    '    dPianCha(1) = gTBCheck(1).Inputs.Item("d1").Value()
    '    uPianCha(2) = gTBCheck(1).Inputs.Item("u2").Value()
    '    dPianCha(2) = gTBCheck(1).Inputs.Item("d2").Value()
    '    uPianCha(3) = gTBCheck(1).Inputs.Item("u3").Value()
    '    dPianCha(3) = gTBCheck(1).Inputs.Item("d3").Value()
    '    uPianCha(4) = gTBCheck(1).Inputs.Item("u4").Value()
    '    dPianCha(4) = gTBCheck(1).Inputs.Item("d4").Value()
    '    uPianCha(5) = gTBCheck(1).Inputs.Item("u5").Value()
    '    dPianCha(5) = gTBCheck(1).Inputs.Item("d5").Value()
    '    uPianCha(6) = gTBCheck(1).Inputs.Item("u6").Value()
    '    dPianCha(6) = gTBCheck(1).Inputs.Item("d6").Value()
    '    uPianCha(7) = gTBCheck(1).Inputs.Item("u7").Value()
    '    dPianCha(7) = gTBCheck(1).Inputs.Item("d7").Value()

    '    gTBCheck(cur_cam_num).Run() '运行图像处理工具
    '    tmpfifo = gTBCheck(cur_cam_num).Tools.Item("相机设定")
    '    If gTBCheck(cur_cam_num).RunStatus.Result = CogToolResultConstants.Accept Then '如果运行成功
    '        '           gPosResult(cur_cam_num).IsPass = gTBCheck(cur_cam_num).Outputs.Item("IsPass").Value() '获取最终判断值
    '        c1 = gTBCheck(cur_cam_num).Outputs.Item("c1").Value()
    '        c2 = gTBCheck(cur_cam_num).Outputs.Item("c2").Value()
    '        score1 = gTBCheck(cur_cam_num).Outputs.Item("Score1").Value()
    '        score2 = gTBCheck(cur_cam_num).Outputs.Item("Score2").Value()
    '        scorelimit = gTBCheck(cur_cam_num).Outputs.Item("Score2").Value()
    '        scorelimit = gTBCheck(cur_cam_num).Outputs.Item("scorelimit").Value()
    '        If c1 = 1 And c2 = 1 And score1 > scorelimit And score2 > scorelimit Then
    '            gPosResult(cur_cam_num).IsPass = True
    '        Else
    '            gPosResult(cur_cam_num).IsPass = False

    '        End If

    '        gPosResult(cur_cam_num).ErrCode = ERRCODE.Ok
    '        '   WriteInspecLog(TSLog, cur_cam_num.ToString & vbTab & gPosResult(0).IsPass) '结果写入log
    '        '  ToolResultShow(gTBCheck(cur_cam_num)) '在信息 栏显示结果+
    '    Else '运行出错
    '        gPosResult(cur_cam_num).IsPass = False

    '        gPosResult(cur_cam_num).ErrCode = ERRCODE.NG
    '        '     ToolResultShow(gTBCheck(cur_cam_num)) '在信息 栏显示结果
    '        '           WriteInspecLog(TSLog, cur_cam_num.ToString & vbTab & "CheckImageProcessErr" & vbTab & gTBCheck(cur_cam_num).RunStatus.Message) '错误信息写入log
    '    End If
    '    If gPosResult(cur_cam_num).IsPass Then
    '        gPassNumCam(cur_cam_num) += 1
    '        ' TxtResult1.Text += "相机" + (cur_cam_num + 1).ToString + "检测结果：PASS" + vbCrLf   '界面显示结果
    '    Else
    '        ' TxtResult1.Text += "相机" + (cur_cam_num + 1).ToString + "检测结果：NG" + vbCrLf   '界面显示结果
    '    End If
    '    CogRecordDisplay1.Image = tmpfifo.OutputImage
    '    CogRecordDisplay1.Fit()
    '    CogRecordDisplay1.Record = gTBCheck(cur_cam_num).CreateLastRunRecord

    '    Dim left, right As Double '左右峰值
    '    Dim ulimit, dlimit As Double '上下限

    '    cur_cam_num = 1   '　处理第二个相机设定
    '    gTotalNumCam(cur_cam_num) += 1
    '    '       uPianCha(0) = gTBCheck(cur_cam_num).Inputs.Item("u0").Value()
    '    '       dPianCha(0) = gTBCheck(cur_cam_num).Inputs.Item("d0").Value()
    '    '       uPianCha(1) = gTBCheck(cur_cam_num).Inputs.Item("u1").Value()
    '    '       dPianCha(1) = gTBCheck(cur_cam_num).Inputs.Item("d1").Value()
    '    '       uPianCha(2) = gTBCheck(cur_cam_num).Inputs.Item("u2").Value()
    '    '       dPianCha(2) = gTBCheck(cur_cam_num).Inputs.Item("d2").Value()
    '    '       uPianCha(3) = gTBCheck(cur_cam_num).Inputs.Item("u3").Value()
    '    '       dPianCha(3) = gTBCheck(cur_cam_num).Inputs.Item("d3").Value()
    '    '       uPianCha(4) = gTBCheck(cur_cam_num).Inputs.Item("u4").Value()
    '    '       dPianCha(4) = gTBCheck(cur_cam_num).Inputs.Item("d4").Value()
    '    '       uPianCha(5) = gTBCheck(cur_cam_num).Inputs.Item("u5").Value()
    '    '       dPianCha(5) = gTBCheck(cur_cam_num).Inputs.Item("d5").Value()
    '    '       uPianCha(6) = gTBCheck(cur_cam_num).Inputs.Item("u6").Value()
    '    '       dPianCha(6) = gTBCheck(cur_cam_num).Inputs.Item("d6").Value()
    '    '       uPianCha(7) = gTBCheck(cur_cam_num).Inputs.Item("u7").Value()
    '    '       dPianCha(7) = gTBCheck(cur_cam_num).Inputs.Item("d7").Value()
    '    gTBCheck(cur_cam_num).Inputs.Item("cu").Value = uPianCha(strNum)
    '    gTBCheck(cur_cam_num).Inputs.Item("cd").Value = dPianCha(strNum)
    '    gTBCheck(cur_cam_num).Run() '运行图像处理工具
    '    tmpfifo = gTBCheck(cur_cam_num).Tools.Item("相机设定")
    '    If gTBCheck(cur_cam_num).RunStatus.Result = CogToolResultConstants.Accept Then '如果运行成功
    '        left = gTBCheck(cur_cam_num).Outputs.Item("Y1").Value()
    '        right = gTBCheck(cur_cam_num).Outputs.Item("Y2").Value()

    '        '       If test = True Then
    '        '          strNum = TxtScrewIndex1.    .Text.Single
    '        ' End If

    '        ulimit = uPianCha(strNum)     'gTBCheck(cur_cam_num).Outputs.Item("uline").Value() + uPianCha(strNum)
    '        dlimit = dPianCha(strNum)   'gTBCheck(cur_cam_num).Outputs.Item("dline").Value() + dPianCha(strNum)
    '        udlimit = gTBCheck(cur_cam_num).Inputs.Item("ULLimit").Value()

    '        If left > ulimit And left < dlimit _
    '            And Int(right) >= Int(ulimit) And Int(right) <= Int(dlimit) _
    '            And Int(udlimit) >= Int(Math.Abs(left - right)) Then
    '            gPosResult(cur_cam_num).IsPass = True
    '            gPosResult(cur_cam_num).ErrCode = ERRCODE.Ok
    '            '              WriteInspecLog(TSLog, cur_cam_num.ToString & vbTab & gPosResult(0).IsPass) '结果写入log
    '            ToolResultShow(gTBCheck(cur_cam_num)) '在信息 栏显示结果+
    '        Else 'false
    '            gPosResult(cur_cam_num).IsPass = False
    '            gPosResult(cur_cam_num).ErrCode = ERRCODE.NG
    '            ToolResultShow(gTBCheck(cur_cam_num)) '在信息 栏显示结果
    '            '          WriteInspecLog(TSLog, cur_cam_num.ToString & vbTab & "CheckImageProcessErr" & vbTab & gTBCheck(cur_cam_num).RunStatus.Message) '错误信息写入log
    '        End If
    '    Else '运行出错
    '        gPosResult(cur_cam_num).ErrCode = ERRCODE.NG
    '        ToolResultShow(gTBCheck(cur_cam_num)) '在信息 栏显示结果
    '        '       WriteInspecLog(TSLog, cur_cam_num.ToString & vbTab & "CheckImageProcessErr" & vbTab & gTBCheck(cur_cam_num).RunStatus.Message) '错误信息写入log
    '    End If
    '    If gPosResult(cur_cam_num).IsPass Then
    '        gPassNumCam(cur_cam_num) += 1
    '        ' TxtResult1.Text += "相机" + (cur_cam_num + 1).ToString + "检测结果：PASS" + vbCrLf   '界面显示结果
    '    Else
    '        ' TxtResult1.Text += "相机" + (cur_cam_num + 1).ToString + "检测结果：NG" + vbCrLf   '界面显示结果
    '    End If

    '    'CogRecordDisplay2.Image = tmpfifo.OutputImage
    '    'CogRecordDisplay2.Fit()
    '    'CogRecordDisplay2.Record = gTBCheck(cur_cam_num).CreateLastRunRecord

    '    '综合判断
    '    Dim TotalResult As Boolean = True
    '    Dim temp As Boolean

    '    For cur_cam_num = 0 To Cam_num - 1 '　逐个处理每个相机设定的结果
    '        temp = gPosResult(cur_cam_num).IsPass
    '        TotalResult = TotalResult And temp
    '        ' TotalResult = TotalResult And gPosResult(cur_cam_num).IsPass
    '        '        RestData(cur_cam_num)
    '    Next
    '    TxtResult1.Text = ""
    '    If c1 = 1 Then
    '        TxtResult1.Text &= "Score1：" + Format(gTBCheck(0).Outputs.Item("Score1").Value, "0.00").ToString + vbCrLf
    '    Else
    '        TxtResult1.Text &= "Score1：" + "0.00" + vbCrLf
    '    End If
    '    If c2 = 1 Then
    '        TxtResult1.Text &= "Score2：" + Format(gTBCheck(0).Outputs.Item("Score2").Value, "0.00").ToString + vbCrLf
    '    Else
    '        TxtResult1.Text &= "Score2：" + "0.00" + vbCrLf
    '    End If
    '    If gPosResult(0).IsPass = True Then
    '        TxtResult1.Text &= "相机1：" + "True" + vbCrLf 'gPosResult(0).IsPass.ToString
    '    Else
    '        TxtResult1.Text &= "相机1：" + "False" + vbCrLf
    '    End If
    '    '       TxtResult1.Text &= "相机1：" + gPosResult(0).IsPass.ToString + vbCrLf
    '    TxtResult1.Text &= "Y1:  " + Format(gTBCheck(1).Outputs.Item("Y1").Value, "0.00").ToString + vbCrLf
    '    TxtResult1.Text &= "Y2:  " + Format(gTBCheck(1).Outputs.Item("Y2").Value, "0.00").ToString + vbCrLf
    '    TxtResult1.Text &= "左右差：" + Format(Math.Abs(left - right), "0.00").ToString + vbCrLf
    '    TxtResult1.Text &= "Ulimit: " + Format(ulimit, "0.00").ToString + vbCrLf
    '    TxtResult1.Text &= "Dlimit: " + Format(dlimit, "0.00").ToString + vbCrLf
    '    TxtResult1.Text &= "左右差limit：" + Format(udlimit, "0.00").ToString + vbCrLf
    '    If gPosResult(1).IsPass = True Then
    '        TxtResult1.Text &= "相机2：" + "True" + vbCrLf 'gPosResult(0).IsPass.ToString
    '    Else
    '        TxtResult1.Text &= "相机2：" + "False" + vbCrLf
    '    End If
    '    '    TxtResult1.Text &= "相机2：" + gPosResult(1).IsPass.ToString + vbCrLf
    '    If TotalResult Then
    '        gPassNum += 1
    '        TxtResult1.Text += "检测结果：" + "PASS" + vbCrLf   '界面显示结果
    '        SP1.Write("1")       '"OK"
    '        If strNum = 0 Then
    '            ok00.Text = "OK"
    '            ok00.ForeColor = Color.Green

    '        ElseIf strNum = 1 Then
    '            ok01.Text = "OK"
    '            ok01.ForeColor = Color.Green
    '        ElseIf strNum = 2 Then
    '            ok02.Text = "OK"
    '            ok02.ForeColor = Color.Green
    '        ElseIf strNum = 3 Then
    '            ok03.Text = "OK"
    '            ok03.ForeColor = Color.Green
    '        ElseIf strNum = 4 Then
    '            ok04.Text = "OK"
    '            ok04.ForeColor = Color.Green
    '        ElseIf strNum = 5 Then
    '            ok05.Text = "OK"
    '            ok05.ForeColor = Color.Green
    '        ElseIf strNum = 6 Then
    '            ok06.Text = "OK"
    '            ok06.ForeColor = Color.Green
    '        ElseIf strNum = 7 Then
    '            ok07.Text = "OK"
    '            ok07.ForeColor = Color.Green
    '        End If

    '    Else
    '        TxtResult1.Text += "检测结果：" + "NG" + vbCrLf   '界面显示结果
    '        SP1.Write("2")                '"NG"

    '        If strNum = 0 Then
    '            ok00.Text = "NG"
    '            ok00.ForeColor = Color.Red
    '        ElseIf strNum = 1 Then
    '            ok01.Text = "NG"
    '            ok01.ForeColor = Color.Red
    '        ElseIf strNum = 2 Then
    '            ok02.Text = "NG"
    '            ok02.ForeColor = Color.Red
    '        ElseIf strNum = 3 Then
    '            ok03.Text = "NG"
    '            ok03.ForeColor = Color.Red
    '        ElseIf strNum = 4 Then
    '            ok04.Text = "NG"
    '            ok04.ForeColor = Color.Red
    '        ElseIf strNum = 5 Then
    '            ok05.Text = "NG"
    '            ok05.ForeColor = Color.Red
    '        ElseIf strNum = 6 Then
    '            ok06.Text = "NG"
    '            ok06.ForeColor = Color.Red
    '        ElseIf strNum = 7 Then
    '            ok07.Text = "NG"
    '            ok07.ForeColor = Color.Red
    '        End If
    '    End If

    '    For cur_cam_num = 0 To Cam_num - 1 '　逐个处理每个相机设定的结果
    '        RestData(cur_cam_num)
    '    Next

    '    '写入显示状态
    '    WriteStatic()
    'End Sub
    'toolBlock结果显示
    Private Sub ToolResultShow(ByRef mytoolblock As CogToolBlock)
        For i = 0 To mytoolblock.Outputs.Count - 1
            If mytoolblock.Outputs.Item(i).Name <> "IsPass" Then
                If mytoolblock.Outputs.Item(i).HasChanged Then
                    TxtResult1.Text += mytoolblock.Outputs.Item(i).Name + ":" + vbTab +
                                       Format(mytoolblock.Outputs.Item(i).Value, "0.000").ToString + vbCrLf
                Else
                    TxtResult1.Text += mytoolblock.Outputs.Item(i).Name + ":" + vbTab +
                                       "None" + vbCrLf
                End If
            End If
        Next
    End Sub

    '整理资源
    Private Sub TimerRubish_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TimerRubish.Tick
        GC.Collect()
    End Sub

    '重置数据
    Private Sub RestData(ByVal cur_cam_num As Integer)
        gPosResult(cur_cam_num).x = 0 '获取X值
        gPosResult(cur_cam_num).y = 0 '获取Y值
        gPosResult(cur_cam_num).r = 0 '获取R值
        gPosResult(cur_cam_num).ErrCode = ERRCODE.NG
        gPosResult(cur_cam_num).IsPass = False
    End Sub

    '刷新界面
    Public Sub WriteStatic(Optional ByVal processtime As Double = 0)
        '相机1
        mut.WaitOne()
        '     TxtTotal1.Text = gTotalNum
        '    TxtPass1.Text = gPassNum
        '    TxtNg1.Text = gTotalNum - gPassNum
        '   If gTotalNumCam(0) <> 0 Then
        '        TxtRate1.Text = Format(gPassNum / gTotalNum * 100, "0.00") + "%"
        '   Else
        '      TxtRate1.Text = 0
        '   End If
        '   TxtResult1.Text += vbCrLf & processtime.ToString & "ms"
        mut.ReleaseMutex()
    End Sub

    '测试用
    Dim test As Boolean

    Private Sub TestToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
        TxtResult1.Text = ""
        Dim __time As DateTime = DateTime.Now
        Dim __timeTotal As DateTime
        '      If gCheckIndex = 1 Then
        __timeTotal = DateTime.Now
        '      End If
        '开始检测
        test = True

    End Sub

    Private Sub TSIsRun_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TSIsRun.Click
        'If TSIsRun.Text = "运行中……" Then
        '    gIsRun = False
        '    TSIsRun.Text = "停止中……"
        'TSIsRun.BackColor = Color.Red
        '    FrmAdmin.EnableMenu()
        '    TSGrabContinues1.Enabled = True
        '    'TSGrabContinues2.Enabled = True
        '    'TSGrabContinues3.Enabled = True
        '    'TSGrabContinues4.Enabled = True
        'Else
        '    gIsRun = True
        '    TSIsRun.Text = "运行中……"
        '    TSIsRun.BackColor = Color.Green
        '    FrmAdmin.EnableMenu()
        '    TSGrabContinues1.Enabled = False
        '    'TSGrabContinues2.Enabled = False
        '    'TSGrabContinues3.Enabled = False
        '    'TSGrabContinues4.Enabled = False
        'End If
    End Sub

    Private Sub TSRest_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TSRest.Click
        Dim i As Integer
        For i = 0 To Cam_num - 1
            gTotalNumCam(i) = 0
            gPassNumCam(i) = 0
        Next
        gTotalNum = 0
        gPassNum = 0
        WriteStatic()
    End Sub

    Private Sub ToolStripButton17_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripButton17.Click
        If TCmbPro.Text <> "" Then
            initPro(TCmbPro.Text)
            InitSetting()
            ' initFailPoint(TCmbPro.Text)
            'CadToRobot()
            'LoadAccess()
            'WriteDeviceRandom_PLC(AxActUtlType1)
        Else
            MsgBox("请先选择产品！")
        End If
    End Sub

    Private Sub BtnResetIndex_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
        gCheckIndex = 1
        WriteStatic()
        '      TxtScrewIndex1.Text = gCheckIndex 'x显示但前步骤
    End Sub

    Private Sub TimerIO_Tick(ByVal sender As Object, ByVal e As System.EventArgs) Handles TimerIO.Tick
        Select Case FirstCCDState
            Case CCDRunStateInfo.SetError
                AppendInfoToTextBox("相机1序列号设置错误")
            Case CCDRunStateInfo.Unconected
                AppendInfoToTextBox("相机1未连接")
            Case CCDRunStateInfo.NoImage
                AppendInfoToTextBox("相机1多次未获取到图像，请检查相机网线连接")
        End Select

        Select Case SecondCCDState
            Case CCDRunStateInfo.SetError
                AppendInfoToTextBox("相机2序列号设置错误")
            Case CCDRunStateInfo.Unconected
                AppendInfoToTextBox("相机2未连接")
            Case CCDRunStateInfo.NoImage
                AppendInfoToTextBox("相机2多次未获取到图像，请检查相机网线连接")
        End Select
    End Sub

    Private Sub FrmMain_FormClosed(ByVal sender As System.Object, ByVal e As System.Windows.Forms.FormClosedEventArgs) Handles MyBase.FormClosed
        'UpLoadComplete_flag = False
        'DataByReal.Status = "Off"
        'DataByReal.Errcode = Nothing
        machineInfoStatus.Status = "4" 'XCPro关机
        machineInfoStatus.ErrorCode = ""
        'uploadstate()
        'upload_MainInfo()
        'waitstandby(100)
        'CloseUploadProcess()
        wait(500)
        If My.Application.OpenForms.Item("FormIO") IsNot Nothing Then
            FormIO.Close()
        End If

        'CloseUploadProcess()

        '判断RT ToolBox2是否在运行
        For Each pro As Process In Process.GetProcesses()
            If pro.ProcessName = "MELFA_RT" Then
                GoTo d
            End If
        Next

        '关闭连接
        Dim TargetKill() As Process = Process.GetProcessesByName("RoboCom") '从进程名获取进程
        If TargetKill.Length > 0 Then
            For i = 0 To (TargetKill.Length - 1)
                TargetKill(i).Kill()
            Next
        End If
d:

        Application.Exit()

        End
    End Sub

    Public Function CRC16(ByVal STR1 As String) As String
        Dim CRCREG As Long            '定义CRC寄存器
        Dim MVAL As Long
        Dim R As Integer

        CRCREG = 65535                '把寄存器各位都置为1

        If (Len(STR1) Mod 2 = 1) Then
            STR1 = "0" & STR1             '当输入的数字串不是偶个数时，在前面补0
        End If

        For R = 1 To Len(STR1) Step 2
            MVAL = Val("&H" + Mid(STR1, R, 2))     '提取输入的数的前两位，转换为十六进制的

            CRCREG = CRCREG Xor MVAL
            'CRCREG = CRCREG And 65535

            For T = 1 To 8 Step 1
                If (CRCREG And &H1) Then
                    CRCREG = (CRCREG \ 2) Xor &HA001
                    CRCREG = CRCREG And 65535
                Else
                    CRCREG = CRCREG \ 2
                    'CRCREG = CRCREG And 65535
                End If
            Next

        Next

        Dim A As Long
        Dim B As Long
        A = CRCREG And 255          '取低八位
        B = CRCREG And 65280        '取高八位
        A = A * 256                 '低八位变成高八位
        B = B / 256                 '高八位变成低八位
        If (A + B) < 16 Then
            CRC16 = "000" + Hex(A + B)
        ElseIf (A + B) < 256 Then
            CRC16 = "00" + Hex(A + B)
        ElseIf (A + B) < 4096 Then
            CRC16 = "0" + Hex(A + B)
        Else
            CRC16 = Hex(A + B)
        End If

    End Function

    Public Function ReadPLCData(ByVal StartAddress As Integer, ByVal DataLength As String) As String
        Dim SendPLCData As String
        SendPLCData = &H3 & &H3 & Hex(StartAddress) & Hex(DataLength)
        SendPLCData += CRC16(SendPLCData)
        'TextBox1.Text += vbLf + SendPLCData
        'SendModbusToPLC(SendPLCData)
    End Function

    Public Function SendModbusToPLC(ByVal SendToPLCData As String) As String  '发送

        '      SendToPLCData = "01 03"
        Dim TestArray() As String = Split(SendToPLCData)
        Dim hexBytes() As Byte
        Dim SendToPLCDataUseRCR(TestArray.Length - 1) As Byte

        ReDim hexBytes(TestArray.Length - 1)
        Dim i As Integer
        Dim CRCValue As String
        Dim CRCValue_H(1) As Byte
        CRCValue = ""
        For i = 0 To TestArray.Length - 1
            hexBytes(i) = Val("&h" & TestArray(i))
            '           SendToPLCDataUseRCR(i) = TestArray(i)
            CRCValue += TestArray(i)
        Next
        '      hexBytes(2) = CRC16(Str(hexBytes))
        '    For i = 0 To TestArray.Length - 1
        'CRCValue = SendToPLCDataUseRCR
        '   CRCValue = StrConv(SendToPLCDataUseRCR)
        '    SP1.Write(hexBytes, 0, hexBytes.Length)

        CRCValue_H(0) = Val("&H" + Mid(CRC16(CRCValue), 1, 2))
        CRCValue_H(1) = Val("&H" + Mid(CRC16(CRCValue), 3, 2))
        Dim SendhexBytes(hexBytes.Length + 1) As Byte
        SendhexBytes = hexBytes.Concat(CRCValue_H).ToArray
        SP1.Write(SendhexBytes, 0, SendhexBytes.Length)
    End Function

    Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
        ReadPLCData(200, 2)
    End Sub

    Private Sub Button7_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)

        RunningCCD = True

    End Sub

    Private Sub Button8_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
        RunningCCD = False
    End Sub

    Private Sub 故障处理设置ToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
        frmAlarmSet.ShowDialog()
    End Sub

    Private Sub TimerModbus_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TimerModbus.Tick

        If ThirdRobotProduct = "" Then
            ThirdRobotProduct = FourthRobotProduct
            FourthRobotProduct = ""
        End If
        If SecondRobotProduct = "" Then
            SecondRobotProduct = ThirdRobotProduct
            ThirdRobotProduct = ""
        End If
        If SendProduct = "" Then
            SendProduct = SecondRobotProduct
            SecondRobotProduct = ""
        End If

        Try
            If NoProduct Then
                Dim SN As String = ""
                Dim Name As String = ""
                If newset(2) = False And SendProduct <> "" And SendProduct <> "PASS" Then
                    AppendInfoToTextBox(SendProduct & vbCrLf)
                    SN = SendProduct.Split(",")(1)
                    Name = SendProduct.Split(",")(0)
                    ChangePro(Name)
                    AppendInfoToTextBox("SN:" & SN & vbCrLf)
                    AppendInfoToTextBox("切换机种：" & Name & vbCrLf)
                    SN_Socket.Send(Encoding.ASCII.GetBytes(Name & vbCrLf))
                    SendProduct = ""
                    NoProduct = False
                    NewNameAndSN.ChanpinName = Name
                    NewNameAndSN.ChanpinSN = SN
                ElseIf newset(2) = False And SendProduct <> "" And SendProduct = "PASS" Then
                    SN = ""
                    Name = SendProduct
                    AppendInfoToTextBox("切换机种：" & SendProduct & vbCrLf)
                    ChangePro(SendProduct)
                    SN_Socket.Send(Encoding.ASCII.GetBytes(SendProduct & vbCrLf))
                    SendProduct = ""
                    NoProduct = False
                    NewNameAndSN.ChanpinName = Name
                    NewNameAndSN.ChanpinSN = SN
                End If

            End If
        Catch ex As Exception
            AppendInfoToTextBox("TimerModbus_Tick:" & ex.Message.ToString & ex.StackTrace.ToString)
            SendProduct = ""
            NoProduct = False
        End Try
    End Sub

    Public Function DecToHex(ByVal DecNumber As Byte) As String
        If DecNumber <= 15 Then
            DecToHex = "0" & Hex(DecNumber)
        Else : DecToHex = Hex(DecNumber)
        End If
        If DecNumber = 0 Then
            DecToHex = "00"
        End If
    End Function

    Private Sub Timerclear_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timerclear.Tick
        Try

            If newset(6) = True And (Now.Hour = Clear_Time Or Now.Hour = Clear_Time + 12) And Now.Minute = 0 Then
                Todaycount.NGCount = 0
                Todaycount.PassCount = 0
                Todaycount.SCount = 0
                Todaycount.Screwcount = 0
                Todaycount.ScrewFailed1 = 0
                Todaycount.ScrewFailed2 = 0
                Todaycount.ScrewFailed3 = 0
                Todaycount.ScrewFailed4 = 0
                Todaycount.ScrewFailed5 = 0
                Todaycount.ScrewFailed6 = 0
                Todaycount.ScrewFailed7 = 0
                Todaycount.ScrewFailed8 = 0
                Todaycount.ScrewFailed9 = 0
                Todaycount.ScrewFailed10 = 0
                Todaycount.ScrewFailed11 = 0
                Todaycount.ScrewFailed12 = 0
                Todaycount.ScrewFailed13 = 0
                Todaycount.ScrewFailed14 = 0
                Todaycount1.ScrewFailed15 = 0
                Todaycount1.ScrewFailed16 = 0
                Todaycount1.ScrewFailed17 = 0
                Todaycount1.ScrewFailed18 = 0
                Todaycount1.ScrewFailed19 = 0
                Todaycount1.ScrewFailed20 = 0
                Todaycount1.ScrewFailed21 = 0
                Todaycount1.ScrewFailed22 = 0
                Todaycount1.ScrewFailed23 = 0
                Todaycount1.ScrewFailed24 = 0
                Todaycount1.ScrewFailed25 = 0
                Todaycount1.ScrewFailed26 = 0
                Todaycount1.ScrewFailed27 = 0
                Todaycount1.ScrewFailed28 = 0
                Todaycount1.ScrewFailed29 = 0
                Todaycount1.ScrewFailed30 = 0
                Todaycount.SFTime = 0
                Todaycount.IDELTime = 0
                Todaycount.ShutDownTime = 0
                TextBox1.Text = Todaycount.PassCount.ToString
                TextBox2.Text = Todaycount.NGCount.ToString
                TextBox3.Text = Todaycount.SCount.ToString
                TextBox6.Text = Todaycount.Screwcount.ToString
                ScrewFailed1.Text = Todaycount.ScrewFailed1.ToString
                ScrewFailed2.Text = Todaycount.ScrewFailed2.ToString
                ScrewFailed3.Text = Todaycount.ScrewFailed3.ToString
                ScrewFailed4.Text = Todaycount.ScrewFailed4.ToString
                ScrewFailed5.Text = Todaycount.ScrewFailed5.ToString
                ScrewFailed6.Text = Todaycount.ScrewFailed6.ToString
                ScrewFailed7.Text = Todaycount.ScrewFailed7.ToString
                ScrewFailed8.Text = Todaycount.ScrewFailed8.ToString
                ScrewFailed9.Text = Todaycount.ScrewFailed9.ToString
                ScrewFailed10.Text = Todaycount.ScrewFailed10.ToString
                ScrewFailed11.Text = Todaycount.ScrewFailed11.ToString
                ScrewFailed12.Text = Todaycount.ScrewFailed12.ToString
                ScrewFailed13.Text = Todaycount.ScrewFailed13.ToString
                ScrewFailed14.Text = Todaycount.ScrewFailed14.ToString
                ScrewFailed15.Text = Todaycount1.ScrewFailed15.ToString
                ScrewFailed16.Text = Todaycount1.ScrewFailed16.ToString
                ScrewFailed17.Text = Todaycount1.ScrewFailed17.ToString
                ScrewFailed18.Text = Todaycount1.ScrewFailed18.ToString
                ScrewFailed19.Text = Todaycount1.ScrewFailed19.ToString
                ScrewFailed20.Text = Todaycount1.ScrewFailed20.ToString
                ScrewFailed21.Text = Todaycount1.ScrewFailed21.ToString
                ScrewFailed22.Text = Todaycount1.ScrewFailed22.ToString
                ScrewFailed23.Text = Todaycount1.ScrewFailed23.ToString
                ScrewFailed24.Text = Todaycount1.ScrewFailed24.ToString
                ScrewFailed25.Text = Todaycount1.ScrewFailed25.ToString
                ScrewFailed26.Text = Todaycount1.ScrewFailed26.ToString
                ScrewFailed27.Text = Todaycount1.ScrewFailed27.ToString
                ScrewFailed28.Text = Todaycount1.ScrewFailed28.ToString
                ScrewFailed29.Text = Todaycount1.ScrewFailed29.ToString
                ScrewFailed30.Text = Todaycount1.ScrewFailed30.ToString
                SFTime.Text = Todaycount.SFTime
                IDELTime.Text = Todaycount.IDELTime
                SDTime.Text = Todaycount.ShutDownTime

                Todaycount2.CycleTime = 0
                Todaycount2.PCSFailed = 0
                Todaycount2.SuctionCount = 0
                Todaycount2.Height_float = 0
                TextBox_CT.Text = 0
                TextBox_PCSFailed.Text = 0
                Suction = 0
                '异常管理
                'ScrewFailed_1.Text = Todaycount.ScrewFailed1.ToString
                'ScrewFailed_2.Text = Todaycount.ScrewFailed2.ToString
                'ScrewFailed_3.Text = Todaycount.ScrewFailed3.ToString
                'ScrewFailed_4.Text = Todaycount.ScrewFailed4.ToString
                'ScrewFailed_5.Text = Todaycount.ScrewFailed5.ToString
                'ScrewFailed_6.Text = Todaycount.ScrewFailed6.ToString
                'ScrewFailed_7.Text = Todaycount.ScrewFailed7.ToString
                'ScrewFailed_8.Text = Todaycount.ScrewFailed8.ToString
                'ScrewFailed_9.Text = Todaycount.ScrewFailed9.ToString
                'ScrewFailed_10.Text = Todaycount.ScrewFailed10.ToString
                'ScrewFailed_11.Text = Todaycount.ScrewFailed11.ToString
                'ScrewFailed_12.Text = Todaycount.ScrewFailed12.ToString
                'ScrewFailed_13.Text = Todaycount.ScrewFailed13.ToString
                'ScrewFailed_14.Text = Todaycount.ScrewFailed14.ToString
                'ScrewFailed_15.Text = Todaycount1.ScrewFailed15.ToString
                'ScrewFailed_16.Text = Todaycount1.ScrewFailed16.ToString
                'ScrewFailed_17.Text = Todaycount1.ScrewFailed17.ToString
                'ScrewFailed_18.Text = Todaycount1.ScrewFailed18.ToString
                'ScrewFailed_19.Text = Todaycount1.ScrewFailed19.ToString
                'ScrewFailed_20.Text = Todaycount1.ScrewFailed20.ToString
                'ScrewFailed_21.Text = Todaycount1.ScrewFailed21.ToString
                'ScrewFailed_22.Text = Todaycount1.ScrewFailed22.ToString
                'ScrewFailed_23.Text = Todaycount1.ScrewFailed23.ToString
                'ScrewFailed_24.Text = Todaycount1.ScrewFailed24.ToString
                'ScrewFailed_25.Text = Todaycount1.ScrewFailed25.ToString
                'ScrewFailed_26.Text = Todaycount1.ScrewFailed26.ToString
                'ScrewFailed_27.Text = Todaycount1.ScrewFailed27.ToString
                'ScrewFailed_28.Text = Todaycount1.ScrewFailed28.ToString
                'ScrewFailed_29.Text = Todaycount1.ScrewFailed29.ToString
                'ScrewFailed_30.Text = Todaycount1.ScrewFailed30.ToString
                Todaycount3.SkipFailed1 = 0
                Todaycount3.SkipFailed2 = 0
                Todaycount3.SkipFailed3 = 0
                Todaycount3.SkipFailed4 = 0
                Todaycount3.SkipFailed5 = 0
                Todaycount3.SkipFailed6 = 0
                Todaycount3.SkipFailed7 = 0
                Todaycount3.SkipFailed8 = 0
                Todaycount3.SkipFailed9 = 0
                Todaycount3.SkipFailed10 = 0
                Todaycount3.SkipFailed11 = 0
                Todaycount3.SkipFailed12 = 0
                Todaycount3.SkipFailed13 = 0
                Todaycount3.SkipFailed14 = 0
                Todaycount4.SkipFailed15 = 0
                Todaycount4.SkipFailed16 = 0
                Todaycount4.SkipFailed17 = 0
                Todaycount4.SkipFailed18 = 0
                Todaycount4.SkipFailed19 = 0
                Todaycount4.SkipFailed20 = 0
                Todaycount4.SkipFailed21 = 0
                Todaycount4.SkipFailed22 = 0
                Todaycount4.SkipFailed23 = 0
                Todaycount4.SkipFailed24 = 0
                Todaycount4.SkipFailed25 = 0
                Todaycount4.SkipFailed26 = 0
                Todaycount4.SkipFailed27 = 0
                Todaycount4.SkipFailed28 = 0
                Todaycount4.SkipFailed29 = 0
                Todaycount4.SkipFailed30 = 0
                SkipFailed1.Text = Todaycount3.SkipFailed1.ToString
                SkipFailed2.Text = Todaycount3.SkipFailed2.ToString
                SkipFailed3.Text = Todaycount3.SkipFailed3.ToString
                SkipFailed4.Text = Todaycount3.SkipFailed4.ToString
                SkipFailed5.Text = Todaycount3.SkipFailed5.ToString
                SkipFailed6.Text = Todaycount3.SkipFailed6.ToString
                SkipFailed7.Text = Todaycount3.SkipFailed7.ToString
                SkipFailed8.Text = Todaycount3.SkipFailed8.ToString
                SkipFailed9.Text = Todaycount3.SkipFailed9.ToString
                SkipFailed10.Text = Todaycount3.SkipFailed10.ToString
                SkipFailed11.Text = Todaycount3.SkipFailed11.ToString
                SkipFailed12.Text = Todaycount3.SkipFailed12.ToString
                SkipFailed13.Text = Todaycount3.SkipFailed13.ToString
                SkipFailed14.Text = Todaycount3.SkipFailed14.ToString
                SkipFailed15.Text = Todaycount4.SkipFailed15.ToString
                SkipFailed16.Text = Todaycount4.SkipFailed16.ToString
                SkipFailed17.Text = Todaycount4.SkipFailed17.ToString
                SkipFailed18.Text = Todaycount4.SkipFailed18.ToString
                SkipFailed19.Text = Todaycount4.SkipFailed19.ToString
                SkipFailed20.Text = Todaycount4.SkipFailed20.ToString
                SkipFailed21.Text = Todaycount4.SkipFailed21.ToString
                SkipFailed22.Text = Todaycount4.SkipFailed22.ToString
                SkipFailed23.Text = Todaycount4.SkipFailed23.ToString
                SkipFailed24.Text = Todaycount4.SkipFailed24.ToString
                SkipFailed25.Text = Todaycount4.SkipFailed25.ToString
                SkipFailed26.Text = Todaycount4.SkipFailed26.ToString
                SkipFailed27.Text = Todaycount4.SkipFailed27.ToString
                SkipFailed28.Text = Todaycount4.SkipFailed28.ToString
                SkipFailed29.Text = Todaycount4.SkipFailed29.ToString
                SkipFailed30.Text = Todaycount4.SkipFailed30.ToString
            End If

            If Now.Minute = 0 Then
                TxtResult1.Text = ""
                '删除过期图片\上传数据
                DeleteDir(gVisionFailedPath)
            End If

            Dim filepath = DebugPath & "\Tool\"
            If Exists(filepath & "\count.txt") Then
                '       Kill(filepath & "\count.txt")
                FileOpen(file_num_count, filepath & "\count.txt", OpenMode.Random)
                FilePut(file_num_count, Todaycount)
                FileClose(file_num_count)
            End If
            If Exists(filepath & "\count1.txt") Then
                '       Kill(filepath & "\count.txt")
                FileOpen(file_num_count1, filepath & "\count1.txt", OpenMode.Random)
                FilePut(file_num_count1, Todaycount1)
                FileClose(file_num_count1)
            End If
            If Exists(filepath & "\count2.txt") Then
                '       Kill(filepath & "\count.txt")
                FileOpen(file_num_count2, filepath & "\count2.txt", OpenMode.Random)
                FilePut(file_num_count2, Todaycount2)
                FileClose(file_num_count2)
            End If
            If Exists(filepath & "\count3.txt") Then
                'Kill(filepath & TCmbPro.Text & "\count.txt")
                FileOpen(file_num_count, filepath & "\count3.txt", OpenMode.Random)
                FilePut(file_num_count, Todaycount3)
                FileClose(file_num_count)
            End If
            If Exists(filepath & "\count4.txt") Then
                'Kill(filepath & TCmbPro.Text & "\count.txt")
                FileOpen(file_num_count, filepath & "\count4.txt", OpenMode.Random)
                FilePut(file_num_count, Todaycount4)
                FileClose(file_num_count)
            End If
        Catch ex As Exception

        End Try
    End Sub

    Private Sub Button2_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs)
        frmShowAlarm.ShowDialog()
    End Sub

    Private Sub TimerFlag_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TimerFlag.Tick
        Try
            If showSNQueueFlag = True Then
                showSNQueueFlag = False
                ShowCurrentSNListQueue() '切换到显示队列页面时卡死问题
            End If
        Catch ex As Exception
        End Try
        Try
            If Can_Barcode = True Then
                Button11.Text = "读码中"
                Button11.BackColor = Color.Lime
            Else
                Button11.Text = "禁止读码"
                Button11.BackColor = Color.WhiteSmoke
            End If
        Catch ex As Exception
        End Try
        If Flag = "C" Then
            Try
                Flag = "0"
                initPro(TCmbPro.Text)
                InitSetting()
                AppendInfoToTextBox(TCmbPro.Text)
            Catch
                ' MsgBox("未在当前库中找到此产品！")
            End Try
            Flag = "InitProOver"
        End If

        If Flag = "S" Then
            Flag = "0"
            If IsScrewFail = True And Suction = "" Or IsScrewFail = True And Suction = "H" Then '异常台计数
                Todaycount2.PCSFailed += 1
                TextBox_PCSFailed.Text = Todaycount2.PCSFailed.ToString
                IsScrewFail = False
            End If

            If Suction = "" Then
                Todaycount.SCount += 1
                ' FilePut(file_num_count, Todaycount)
                TextBox3.Text = Todaycount.SCount.ToString
            End If

            '单台失败颗数统计
            If Suction = "" Or Suction = "H" Then
                DataByPCS.NGPoint += 1
                SF_Fail_Qty_Single += 1
            End If
            '各个点位失败次数
            If Screw = "1" And Suction = "" Or Screw = "1" And Suction = "H" Then
                Todaycount.ScrewFailed1 += 1
                ScrewFailed1.Text = Todaycount.ScrewFailed1.ToString
                ' ScrewFailed_1.Text = Todaycount.ScrewFailed1.ToString
            End If
            If Screw = "2" And Suction = "" Or Screw = "2" And Suction = "H" Then
                Todaycount.ScrewFailed2 += 1
                ScrewFailed2.Text = Todaycount.ScrewFailed2.ToString
                'ScrewFailed_2.Text = Todaycount.ScrewFailed2.ToString
            End If
            If Screw = "3" And Suction = "" Or Screw = "3" And Suction = "H" Then
                Todaycount.ScrewFailed3 += 1
                ScrewFailed3.Text = Todaycount.ScrewFailed3.ToString
                ' ScrewFailed_3.Text = Todaycount.ScrewFailed3.ToString
            End If
            If Screw = "4" And Suction = "" Or Screw = "4" And Suction = "H" Then
                Todaycount.ScrewFailed4 += 1
                ScrewFailed4.Text = Todaycount.ScrewFailed4.ToString
                ' ScrewFailed_4.Text = Todaycount.ScrewFailed4.ToString
            End If
            If Screw = "5" And Suction = "" Or Screw = "5" And Suction = "H" Then
                Todaycount.ScrewFailed5 += 1
                ScrewFailed5.Text = Todaycount.ScrewFailed5.ToString
                ' ScrewFailed_5.Text = Todaycount.ScrewFailed5.ToString
            End If
            If Screw = "6" And Suction = "" Or Screw = "6" And Suction = "H" Then
                Todaycount.ScrewFailed6 += 1
                ScrewFailed6.Text = Todaycount.ScrewFailed6.ToString
                'ScrewFailed_6.Text = Todaycount.ScrewFailed6.ToString
            End If
            If Screw = "7" And Suction = "" Or Screw = "7" And Suction = "H" Then
                Todaycount.ScrewFailed7 += 1
                ScrewFailed7.Text = Todaycount.ScrewFailed7.ToString
                'ScrewFailed_7.Text = Todaycount.ScrewFailed7.ToString
            End If
            If Screw = "8" And Suction = "" Or Screw = "8" And Suction = "H" Then
                Todaycount.ScrewFailed8 += 1
                ScrewFailed8.Text = Todaycount.ScrewFailed8.ToString
                'ScrewFailed_8.Text = Todaycount.ScrewFailed8.ToString
            End If
            If Screw = "9" And Suction = "" Or Screw = "9" And Suction = "H" Then
                Todaycount.ScrewFailed9 += 1
                ScrewFailed9.Text = Todaycount.ScrewFailed9.ToString
                'ScrewFailed_9.Text = Todaycount.ScrewFailed9.ToString
            End If
            If Screw = "10" And Suction = "" Or Screw = "10" And Suction = "H" Then
                Todaycount.ScrewFailed10 += 1
                ScrewFailed10.Text = Todaycount.ScrewFailed10.ToString
                ' ScrewFailed_10.Text = Todaycount.ScrewFailed10.ToString
            End If
            If Screw = "11" And Suction = "" Or Screw = "11" And Suction = "H" Then
                Todaycount.ScrewFailed11 += 1
                ScrewFailed11.Text = Todaycount.ScrewFailed11.ToString
                'ScrewFailed_11.Text = Todaycount.ScrewFailed11.ToString
            End If
            If Screw = "12" And Suction = "" Or Screw = "12" And Suction = "H" Then
                Todaycount.ScrewFailed12 += 1
                ScrewFailed12.Text = Todaycount.ScrewFailed12.ToString
                'ScrewFailed_12.Text = Todaycount.ScrewFailed12.ToString
            End If
            If Screw = "13" And Suction = "" Or Screw = "13" And Suction = "H" Then
                Todaycount.ScrewFailed13 += 1
                ScrewFailed13.Text = Todaycount.ScrewFailed13.ToString
                'ScrewFailed_13.Text = Todaycount.ScrewFailed13.ToString
            End If
            If Screw = "14" And Suction = "" Or Screw = "14" And Suction = "H" Then
                Todaycount.ScrewFailed14 += 1
                ScrewFailed14.Text = Todaycount.ScrewFailed14.ToString
                ' ScrewFailed_14.Text = Todaycount.ScrewFailed14.ToString
            End If
            If Screw = "15" And Suction = "" Or Screw = "15" And Suction = "H" Then
                Todaycount1.ScrewFailed15 += 1
                ScrewFailed15.Text = Todaycount1.ScrewFailed15.ToString
                ' ScrewFailed_15.Text = Todaycount1.ScrewFailed15.ToString
            End If
            If Screw = "16" And Suction = "" Or Screw = "16" And Suction = "H" Then
                Todaycount1.ScrewFailed16 += 1
                ScrewFailed16.Text = Todaycount1.ScrewFailed16.ToString
                ' ScrewFailed_16.Text = Todaycount1.ScrewFailed16.ToString
            End If
            If Screw = "17" And Suction = "" Or Screw = "17" And Suction = "H" Then
                Todaycount1.ScrewFailed17 += 1
                ScrewFailed17.Text = Todaycount1.ScrewFailed17.ToString
                'ScrewFailed_17.Text = Todaycount1.ScrewFailed17.ToString
            End If
            If Screw = "18" And Suction = "" Or Screw = "18" And Suction = "H" Then
                Todaycount1.ScrewFailed18 += 1
                ScrewFailed18.Text = Todaycount1.ScrewFailed18.ToString
                ' ScrewFailed_18.Text = Todaycount1.ScrewFailed18.ToString
            End If
            If Screw = "19" And Suction = "" Or Screw = "19" And Suction = "H" Then
                Todaycount1.ScrewFailed19 += 1
                ScrewFailed19.Text = Todaycount1.ScrewFailed19.ToString
                ' ScrewFailed_19.Text = Todaycount1.ScrewFailed19.ToString
            End If
            If Screw = "20" And Suction = "" Or Screw = "20" And Suction = "H" Then
                Todaycount1.ScrewFailed20 += 1
                ScrewFailed20.Text = Todaycount1.ScrewFailed20.ToString
                ' ScrewFailed_20.Text = Todaycount1.ScrewFailed20.ToString
            End If
            If Screw = "21" And Suction = "" Or Screw = "21" And Suction = "H" Then
                Todaycount1.ScrewFailed21 += 1
                ScrewFailed21.Text = Todaycount1.ScrewFailed21.ToString
                ' ScrewFailed_21.Text = Todaycount1.ScrewFailed21.ToString
            End If
            If Screw = "22" And Suction = "" Or Screw = "22" And Suction = "H" Then
                Todaycount1.ScrewFailed22 += 1
                ScrewFailed22.Text = Todaycount1.ScrewFailed22.ToString
                ' ScrewFailed_22.Text = Todaycount1.ScrewFailed22.ToString
            End If
            If Screw = "23" And Suction = "" Or Screw = "23" And Suction = "H" Then
                Todaycount1.ScrewFailed23 += 1
                ScrewFailed23.Text = Todaycount1.ScrewFailed23.ToString
                'ScrewFailed_23.Text = Todaycount1.ScrewFailed23.ToString
            End If

            If Screw = "24" And Suction = "" Or Screw = "24" And Suction = "H" Then
                Todaycount1.ScrewFailed24 += 1
                ScrewFailed24.Text = Todaycount1.ScrewFailed24.ToString
                'ScrewFailed_24.Text = Todaycount1.ScrewFailed24.ToString
            End If
            If Screw = "25" And Suction = "" Or Screw = "25" And Suction = "H" Then
                Todaycount1.ScrewFailed25 += 1
                ScrewFailed25.Text = Todaycount1.ScrewFailed25.ToString
                'ScrewFailed_25.Text = Todaycount1.ScrewFailed25.ToString
            End If
            If Screw = "26" And Suction = "" Or Screw = "26" And Suction = "H" Then
                Todaycount1.ScrewFailed26 += 1
                ScrewFailed26.Text = Todaycount1.ScrewFailed26.ToString
                'ScrewFailed_26.Text = Todaycount1.ScrewFailed26.ToString
            End If
            If Screw = "27" And Suction = "" Or Screw = "27" And Suction = "H" Then
                Todaycount1.ScrewFailed27 += 1
                ScrewFailed27.Text = Todaycount1.ScrewFailed27.ToString
                ' ScrewFailed_27.Text = Todaycount1.ScrewFailed27.ToString
            End If
            If Screw = "28" And Suction = "" Or Screw = "28" And Suction = "H" Then
                Todaycount1.ScrewFailed28 += 1
                ScrewFailed28.Text = Todaycount1.ScrewFailed28.ToString
                'ScrewFailed_28.Text = Todaycount1.ScrewFailed28.ToString
            End If
            If Screw = "29" And Suction = "" Or Screw = "29" And Suction = "H" Then
                Todaycount1.ScrewFailed29 += 1
                ScrewFailed29.Text = Todaycount1.ScrewFailed29.ToString
                'ScrewFailed_29.Text = Todaycount1.ScrewFailed29.ToString
            End If
            If Screw = "30" And Suction = "" Or Screw = "30" And Suction = "H" Then
                Todaycount1.ScrewFailed30 += 1
                ScrewFailed30.Text = Todaycount1.ScrewFailed30.ToString
                ' ScrewFailed_30.Text = Todaycount1.ScrewFailed30.ToString
            End If
            If Suction = "H" Then
                Todaycount2.Height_float += 1
                TextBox14.Text = Todaycount2.Height_float.ToString
            End If
        End If

        '漏锁异常各个位点计数
        If Flag = "K" Then
            Flag = "0"
            If IsScrewFail = True Then '异常台计数
                Todaycount2.PCSFailed += 1
                TextBox_PCSFailed.Text = Todaycount2.PCSFailed.ToString
                IsScrewFail = False
            End If

            If Skip = "1" Then
                Todaycount3.SkipFailed1 += 1
                SkipFailed1.Text = Todaycount3.SkipFailed1.ToString
            End If
            If Skip = "2" Then
                Todaycount3.SkipFailed2 += 1
                SkipFailed2.Text = Todaycount3.SkipFailed2.ToString
            End If
            If Skip = "3" Then
                Todaycount3.SkipFailed3 += 1
                SkipFailed3.Text = Todaycount3.SkipFailed3.ToString
            End If
            If Skip = "4" Then
                Todaycount3.SkipFailed4 += 1
                SkipFailed4.Text = Todaycount3.SkipFailed4.ToString
            End If
            If Skip = "5" Then
                Todaycount3.SkipFailed5 += 1
                SkipFailed5.Text = Todaycount3.SkipFailed5.ToString
            End If
            If Skip = "6" Then
                Todaycount3.SkipFailed6 += 1
                SkipFailed6.Text = Todaycount3.SkipFailed6.ToString
            End If
            If Skip = "7" Then
                Todaycount3.SkipFailed7 += 1
                SkipFailed7.Text = Todaycount3.SkipFailed7.ToString
            End If
            If Skip = "8" Then
                Todaycount3.SkipFailed8 += 1
                SkipFailed8.Text = Todaycount3.SkipFailed8.ToString
            End If
            If Skip = "9" Then
                Todaycount3.SkipFailed9 += 1
                SkipFailed9.Text = Todaycount3.SkipFailed9.ToString
            End If
            If Skip = "10" Then
                Todaycount3.SkipFailed10 += 1
                SkipFailed10.Text = Todaycount3.SkipFailed10.ToString
            End If
            If Skip = "11" Then
                Todaycount3.SkipFailed11 += 1
                SkipFailed11.Text = Todaycount3.SkipFailed11.ToString
            End If
            If Skip = "12" Then
                Todaycount3.SkipFailed12 += 1
                SkipFailed12.Text = Todaycount3.SkipFailed12.ToString
            End If
            If Skip = "13" Then
                Todaycount3.SkipFailed13 += 1
                SkipFailed13.Text = Todaycount3.SkipFailed13.ToString
            End If
            If Skip = "14" Then
                Todaycount3.SkipFailed14 += 1
                SkipFailed14.Text = Todaycount3.SkipFailed14.ToString
            End If
            If Skip = "15" Then
                Todaycount4.SkipFailed15 += 1
                SkipFailed15.Text = Todaycount4.SkipFailed15.ToString
            End If
            If Skip = "16" Then
                Todaycount4.SkipFailed16 += 1
                SkipFailed16.Text = Todaycount4.SkipFailed16.ToString
            End If
            If Skip = "17" Then
                Todaycount4.SkipFailed17 += 1
                SkipFailed17.Text = Todaycount4.SkipFailed17.ToString
            End If
            If Skip = "18" Then
                Todaycount4.SkipFailed18 += 1
                SkipFailed18.Text = Todaycount4.SkipFailed18.ToString
            End If
            If Skip = "19" Then
                Todaycount4.SkipFailed19 += 1
                SkipFailed19.Text = Todaycount4.SkipFailed19.ToString
            End If
            If Skip = "20" Then
                Todaycount4.SkipFailed20 += 1
                SkipFailed20.Text = Todaycount4.SkipFailed20.ToString
            End If
            If Skip = "21" Then
                Todaycount4.SkipFailed21 += 1
                SkipFailed21.Text = Todaycount4.SkipFailed21.ToString
            End If
            If Skip = "22" Then
                Todaycount4.SkipFailed22 += 1
                SkipFailed22.Text = Todaycount4.SkipFailed22.ToString
            End If
            If Skip = "23" Then
                Todaycount4.SkipFailed23 += 1
                SkipFailed23.Text = Todaycount4.SkipFailed23.ToString
            End If
            If Skip = "24" Then
                Todaycount4.SkipFailed24 += 1
                SkipFailed24.Text = Todaycount4.SkipFailed24.ToString
            End If
            If Skip = "25" Then
                Todaycount4.SkipFailed25 += 1
                SkipFailed25.Text = Todaycount4.SkipFailed25.ToString
            End If
            If Skip = "26" Then
                Todaycount4.SkipFailed26 += 1
                SkipFailed26.Text = Todaycount4.SkipFailed26.ToString
            End If
            If Skip = "27" Then
                Todaycount4.SkipFailed27 += 1
                SkipFailed27.Text = Todaycount4.SkipFailed27.ToString
            End If
            If Skip = "28" Then
                Todaycount4.SkipFailed28 += 1
                SkipFailed28.Text = Todaycount4.SkipFailed28.ToString
            End If
            If Skip = "29" Then
                Todaycount4.SkipFailed29 += 1
                SkipFailed29.Text = Todaycount4.SkipFailed29.ToString
            End If
            If Skip = "30" Then
                Todaycount4.SkipFailed30 += 1
                SkipFailed30.Text = Todaycount4.SkipFailed30.ToString
            End If
            If Suction = "u" Then
                Todaycount2.SuctionCount += 1
                TextBox5.Text = Todaycount2.SuctionCount.ToString
            End If
        End If
        If Flag = "V" Then
            Flag = "0"
            Todaycount.NGCount += 1
            SB_Fail_Qty_Single += 1
            TextBox2.Text = Todaycount.NGCount.ToString
        End If
        '按台计算良率
        If TextBox1.Text = "0" Then
            TextBox_Yield.Text = "100.00%"
        Else
            Dim OKRate As Double = 100 * (1 - Val(TextBox_PCSFailed.Text) / Val(TextBox1.Text))
            TextBox_Yield.Text = Format(OKRate, "0.00") & "%"
        End If

        DataByPCS.TotalInput = Val(TextBox1.Text)
        DataByPCS.NGInput = Val(TextBox_PCSFailed.Text)

        If DataByPCS.TotalInput - DataByPCS.NGInput > 0 Then
            DataByPCS.OKInput = DataByPCS.TotalInput - DataByPCS.NGInput
        Else
            DataByPCS.OKInput = 0
        End If

        If DataByPCS.TotalInput = 0 Then
            DataByPCS.YieldRate = 1
        Else
            Dim OKRate As Double = 100 * (1 - Val(TextBox_PCSFailed.Text) / Val(TextBox1.Text))
            DataByPCS.YieldRate = OKRate
        End If

    End Sub

    Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
        Dim lngCalculator As IntPtr

        Dim lngStyle As Long
        Try

            lngCalculator = FindWindow(vbNullString, "螺丝机_人机应用_1")
            If lngCalculator Then
                'Dim ps As Process() = Process.GetProcessesByName("PanelSim")
                'For Each p As Process In ps
                '    p.Kill()
                'Next
                'MoveWindow(appwin.ToInt32, -80, -100, 800, 480, 1)
                SetParent(lngCalculator, Me.Panel1.Handle)
                lngStyle = FindWindow(vbNullString, "螺丝机_人机应用_1")
                '       SetWindowLong(lngStyle, GWL_EXSTYLE, WS_EX_MDICHILD)
                MoveWindow(lngCalculator, -78, -98, 870, 580, 1)
                'Panel1.Size = New Size(800, 480)
                TabControl1.SelectedIndex = 0
                Timer1.Enabled = False
            End If

            'robot
            'lngCalculator = FindWindow(vbNullString, "(0/1) - Communication Server2")
            'If lngCalculator Then
            '    'Dim ps As Process() = Process.GetProcessesByName("PanelSim")
            '    'For Each p As Process In ps
            '    '    p.Kill()
            '    'Next
            '    'MoveWindow(appwin.ToInt32, -80, -100, 800, 480, 1)
            '    SetParent(lngCalculator, Me.Panel1.Handle)
            '    lngStyle = FindWindow(vbNullString, "(0/1) - Communication Server2")
            '    '       SetWindowLong(lngStyle, GWL_EXSTYLE, WS_EX_MDICHILD)
            '    MoveWindow(lngCalculator, -78, -98, 870, 580, 1)
            '    'Panel1.Size = New Size(800, 480)
            '    TabControl1.SelectedIndex = 0
            '    Timer1.Enabled = False
            'End If
        Catch ex As Exception

        End Try

    End Sub

    Private Sub Button4_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button4.Click
        FolderBrowserDialog1.ShowDialog()

        Dim ss() As String = FolderBrowserDialog1.SelectedPath.Split("\")
        If ss(ss.Length - 1) <> "VisionFailed" Then
            MsgBox("请指定VisionFailed文件夹！")
            GoTo d
        End If

        gVisionFailedPath = FolderBrowserDialog1.SelectedPath
        If Microsoft.VisualBasic.Right(gVisionFailedPath, 1) <> "\" Then
            gVisionFailedPath += "\"
        End If
        TextBox4.Text = gVisionFailedPath
        SaveSetting("XCPro", "Settings", "VisionFailedPath", gVisionFailedPath)
d:
    End Sub

    Private Sub Stop_Button_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Stop_Button.Click
        If Stop_Button.Text = "Stop" Then
            SN_Focus.Enabled = False
            Stop_Button.Text = "Start"
        ElseIf Stop_Button.Text = "Start" Then
            SN_Focus.Enabled = True
            Stop_Button.Text = "Stop"
        End If

    End Sub

    Private Sub SN_Focus_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SN_Focus.Tick
        SNInputBox.Focus()
    End Sub

    Private Sub 注册RegisteToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles 注册RegisteToolStripMenuItem.Click
        FrmRegister.ShowDialog()
    End Sub

    ' ''' <summary>
    ' ''' 加载设备信息
    ' ''' </summary>
    ' ''' <param ></param>
    ' ''' <remarks></remarks>
    'Sub InitMachineInfo()
    '    Try
    '        Dim filepath = My.Application.Info.DirectoryPath & "\Tool\"
    '        Dim file_num As Integer = FreeFile()
    '        Dim j As Integer = 0
    '        Dim file_exist As Boolean = Exists(filepath & "MachineInfo.txt")
    '        If file_exist = True Then
    '            FileOpen(file_num, filepath & "MachineInfo.txt", OpenMode.Random)
    '            FileGet(file_num, MachineInfo1)
    '            FileClose(file_num)
    '            FrmMachineOld.TextBox_Site.Text = MachineInfo1.Machine_Site
    '            FrmMachineOld.TextBox_Dept.Text = MachineInfo1.Machine_Dept
    '            FrmMachineOld.TextBox_LineID.Text = MachineInfo1.Machine_LineID
    '            FrmMachineOld.TextBox_MIP.Text = MachineInfo1.Machine_MIP
    '            FrmMachineOld.TextBox_MModel.Text = MachineInfo1.Machine_MModel
    '            FrmMachineOld.TextBox_MName.Text = MachineInfo1.Machine_MName
    '            FrmMachineOld.TextBox_MNO.Text = MachineInfo1.Machine_MNO
    '            FrmMachineOld.TextBox_MSN.Text = MachineInfo1.Machine_MSN
    '            FrmMachineOld.TextBox_Plant.Text = MachineInfo1.Machine_Plant
    '            FrmMachineOld.TextBox_KeyType.Text = MachineInfo1.Machine_KeyType
    '            AppendInfoToTextBox("厂  别: " & MachineInfo1.Machine_Plant)
    '            AppendInfoToTextBox("车  间: " & MachineInfo1.Machine_Dept)
    '            AppendInfoToTextBox("LineID: " & MachineInfo1.Machine_LineID)
    '            AppendInfoToTextBox("Name: " & MachineInfo1.Machine_MName)
    '            AppendInfoToTextBox("Model: " & MachineInfo1.Machine_MModel)
    '            AppendInfoToTextBox("SN: " & MachineInfo1.Machine_MSN)
    '            AppendInfoToTextBox("NO: " & MachineInfo1.Machine_MNO)
    '            AppendInfoToTextBox("IP: " & MachineInfo1.Machine_MIP)
    '            AppendInfoToTextBox("StageCode: " & MachineInfo1.Machine_StageCode)
    '            AppendInfoToTextBox("KeyInfoType: " & MachineInfo1.Machine_KeyType & vbCrLf)
    '        Else
    '            FrmMachineOld.TextBox_Dept.Text = ""
    '            FrmMachineOld.TextBox_LineID.Text = ""
    '            FrmMachineOld.TextBox_MIP.Text = ""
    '            FrmMachineOld.TextBox_MModel.Text = ""
    '            FrmMachineOld.TextBox_MName.Text = ""
    '            FrmMachineOld.TextBox_MNO.Text = ""
    '            FrmMachineOld.TextBox_MSN.Text = ""
    '            FrmMachineOld.TextBox_Plant.Text = ""
    '            FrmMachineOld.TextBox_StageCode.Text = ""
    '            FrmMachineOld.TextBox_KeyType.Text = ""
    '            MachineInfo_flag = False
    '            While MachineInfo_flag = False
    '                MsgBox("设备信息未保存设置!!")
    '                FrmMachineOld.ShowDialog()
    '            End While
    '        End If

    '    Catch ex As Exception

    '        MsgBox("InitMachineInfo():设备信息文件错误!" & vbCrLf & ex.Message.ToString)
    '    End Try

    'End Sub

    'Private Sub 设备信息设置ToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles 设备信息设置ToolStripMenuItem.Click

    '    FrmMachineOld.ShowDialog()

    'End Sub

    'Private Sub UpdateByPCS(ByRef TotalPointCount As Integer)
    '    Dim DataPath As String = DebugPath & "\SFCSData\DataByPCS\" & Format(Now, "yyyyMMdd") & "\"
    '    Dim IsRun As Integer = 0
    '    Dim timeNow As String = Format((DateTime.UtcNow - New DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalSeconds * 1000, "000")
    '    Dim UpLoadByPCS As SFCSByPCS = New SFCSByPCS(TotalPointCount - 1)
    '    Dim NullDataByPCS As SFCSByPCS = New SFCSByPCS(30) '生产产品数据0
    '    Try
    '        If Directory.Exists(DataPath) = False Then  '判断文件夹是否存在
    '            Directory.CreateDirectory(DataPath)
    '        End If

    '        '设备信息--10
    '        UpLoadByPCS.Site = MachineInfo1.Machine_Site
    '        UpLoadByPCS.Plant = MachineInfo1.Machine_Plant   '厂别 ----OK
    '        UpLoadByPCS.Dept = MachineInfo1.Machine_Dept    '车间 ----OK
    '        UpLoadByPCS.Line = MachineInfo1.Machine_LineID  '线别 ----OK
    '        UpLoadByPCS.MachineName = MachineInfo1.Machine_MName   '设备名 ----OK
    '        UpLoadByPCS.MachineModel = MachineInfo1.Machine_MModel  '设备型号 ----OK
    '        UpLoadByPCS.MachineSN = MachineInfo1.Machine_MSN '设备SN -----OK
    '        UpLoadByPCS.MachineNO = MachineInfo1.Machine_MNO '设备NO---- OK
    '        UpLoadByPCS.MachineIP = MachineInfo1.Machine_MIP '设备IP ----OK
    '        UpLoadByPCS.evt_dt = timeNow ' time OK
    '        '生产信息
    '        UpLoadByPCS.Program = DataByPCS.Program 'program name,Init Pro中赋值---- OK
    '        NullDataByPCS.Model = DataByPCS.Model   '暂存设备信息，否则不扫码为null

    '        UpLoadByPCS.Model = DataByPCS.Model 'program name,Init Pro中赋值---- OK

    '        UpLoadByPCS.USN = DataByPCS.USN 'SN,Init Pro 中赋值---- OK
    '        UpLoadByPCS.TotalPoint = DataByPCS.TotalPoint 'Total point,产品设置---OK

    '        UpLoadByPCS.NGPoint = DataByPCS.NGPoint ' NG point,机器人上传A screw* ;--OK,第一个拍照点清除

    '        DataByPCS.SkipPoint = DataByPCS.TotalPoint - DataByPCS.NGPoint - ScrewOKCount
    '        UpLoadByPCS.SkipPoint = DataByPCS.SkipPoint 'Skip Point,计算---OK
    '        UpLoadByPCS.SkipPointPICNO = DataByPCS.SkipPointPICNO ' Skip point pic NO
    '        UpLoadByPCS.TotalInput = DataByPCS.TotalInput  '  Total input, TimerFlag中赋值 -----OK
    '        UpLoadByPCS.OKInput = DataByPCS.OKInput 'OK 台数, TimerFlag中赋值 ----OK
    '        UpLoadByPCS.NGInput = DataByPCS.NGInput 'NG 台数, TimerFlag中赋值 ----OK
    '        UpLoadByPCS.YieldRate = DataByPCS.YieldRate 'Yeild rate %, TimerFlag中赋值----- OK
    '        UpLoadByPCS.OperatorID = DataByPCS.OperatorID 'operator ID -----OK
    '        UpLoadByPCS.CameraoffsetX = DataByPCS.CameraoffsetX 'camera offset X1(mm),第一个拍照点偏差 ----OK
    '        UpLoadByPCS.CameraoffsetY = DataByPCS.CameraoffsetY 'camera offset Y1(mm),第一个拍照点偏差 ----OK
    '        'a(22) = "" 'camera offset X2(mm)
    '        'a(23) = "" 'camera offset Y2(mm)
    '        UpLoadByPCS.CameraoffsetUOM = "mm"
    '        UpLoadByPCS.ScrewdriverSpeed = DataByPCS.ScrewdriverSpeed '螺丝枪转速D908
    '        UpLoadByPCS.ScrewdriverSpeedUOM = "r/min"
    '        UpLoadByPCS.AxisSpeedX = DataByPCS.AxisSpeedX ' X axis速度----NA
    '        UpLoadByPCS.AcceTimeX = DataByPCS.AcceTimeX 'X 加速度----NA
    '        UpLoadByPCS.AxisSpeedY = DataByPCS.AxisSpeedY 'Y Axis速度----NA
    '        UpLoadByPCS.AcceTimeY = DataByPCS.AcceTimeY 'Y 加速度----NA
    '        UpLoadByPCS.AxisSpeedZ = DataByPCS.AxisSpeedZ 'Z Axis速度----NA
    '        UpLoadByPCS.AcceTimeZ = DataByPCS.AcceTimeZ 'Z 加速度----NA
    '        UpLoadByPCS.StartTime = DataByPCS.StartTime 'Start time ----OK
    '        UpLoadByPCS.EndTime = DataByPCS.EndTime 'End time,CycleTime上报时间 ----OK
    '        UpLoadByPCS.CycleTime = DataByPCS.CycleTime 'Cycle time,机器人上报---ok
    '        UpLoadByPCS.IsOK = DataByPCS.IsOK 'IsOK,接收result后处理---ok
    '        UpLoadByPCS.NGPICNO = DataByPCS.NGPICNO 'NGPICNO,第二个拍照点处理---ok
    '        '点位信息
    '        For i = 0 To (TotalPointCount - 1) '----OK
    '            UpLoadByPCS.Points(i).NO = (i + 1) 'Point NO
    '            UpLoadByPCS.Points(i).Result = DataByPCS.Points(i).Result  'Point1Result
    '            UpLoadByPCS.Points(i).NGReson = DataByPCS.Points(i).NGReson  'Point1NG Reason
    '            UpLoadByPCS.Points(i).CCDCenterX1 = DataByPCS.Points(i).CCDCenterX1 'CCD centerX1
    '            UpLoadByPCS.Points(i).CCDCenterY1 = DataByPCS.Points(i).CCDCenterY1 'CCD centerY1
    '            UpLoadByPCS.Points(i).CCDCenterX2 = DataByPCS.Points(i).CCDCenterX2 'CCD centerX2
    '            UpLoadByPCS.Points(i).CCDCenterY2 = DataByPCS.Points(i).CCDCenterY2 'CCD centerY3
    '            UpLoadByPCS.Points(i).ScrewPositionX = DataByPCS.Points(i).ScrewPositionX 'ScrewPosition X
    '            UpLoadByPCS.Points(i).ScrewPositionY = DataByPCS.Points(i).ScrewPositionY 'ScrewPosition Y
    '            UpLoadByPCS.Points(i).ScrewPositionZ = DataByPCS.Points(i).ScrewPositionZ 'ScrewPosition Z
    '            UpLoadByPCS.Points(i).ScrewPositionR = DataByPCS.Points(i).ScrewPositionR 'ScrewPosition R
    '        Next
    '        Dim jsonHelper As JsonHelper = New JsonHelper
    '        Dim ss As String = jsonHelper.ToJson(UpLoadByPCS)
    '        Dim saveName As String = DataPath & "BYPCS" & Format(DateTime.Now, "-yyyyMMdd-Hmmss-ffff") & ".json"
    '        Dim Pwrite As New System.IO.StreamWriter(saveName)
    '        Pwrite.Write(ss)
    '        Pwrite.Close()
    '        DataByPCS = NullDataByPCS
    '        ScrewOKCount = 0    '第一个拍照点清除
    '        'File.ReadAllText(DataPath & "BYPCS.json")
    '        Dim WM_SETFOCUS As IntPtr = &H7
    '        Dim WM_SETTEXT As IntPtr = &HC
    '        Dim lngCalculator As IntPtr = FindWindow(vbNullString, "数据上传")
    '        Dim Line As IntPtr = FindWindowEx(lngCalculator, 0, vbNullString, "BYPCS")
    '        Dim j As Integer = SendMessage(Line, WM_SETTEXT, 0, saveName)
    '        If j = 0 Then
    '            AppendInfoToTextBox("异常发送失败,数据上传程序已断开")
    '        End If

    '    Catch ex As Exception
    '        AppendInfoToTextBox(ex.Message.ToString)
    '    End Try
    'End Sub
    'Private Sub UpLoadPIC(ByVal picPath As String)
    '    Try
    '        Dim WM_SETFOCUS As IntPtr = &H7
    '        Dim WM_SETTEXT As IntPtr = &HC
    '        Dim lngCalculator As IntPtr = FindWindow(vbNullString, "数据上传")
    '        Dim Line As IntPtr = FindWindowEx(lngCalculator, 0, vbNullString, "PIC")
    '        Dim j As Integer = SendMessage(Line, WM_SETTEXT, 0, picPath)
    '        If j = 0 Then
    '            AppendInfoToTextBox("异常发送失败,数据上传程序已断开")
    '        End If

    '    Catch ex As Exception

    '    End Try
    'End Sub

    '    Private Sub Uploadstatus_Tick(sender As Object, e As EventArgs)

    '        Dim DataPath As String = My.Application.Info.DirectoryPath & "\SFCSData\DataByReal\" & Format(Now, "yyyMMdd") & "\"
    '        Dim IsRun As Integer = 1
    '        Dim timeNow As String = Format((DateTime.UtcNow - New DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalSeconds * 1000, "000")
    '        Dim UPdataByReal As SFCSByReal = New SFCSByReal

    '        Try
    '            UPloadTime += 0.5
    '            If Directory.Exists(DataPath) = False Then  '判断文件夹是否存在
    '                Directory.CreateDirectory(DataPath)
    '            End If
    '            If initOK_flag = True Then
    '                UPdataByReal.Site = MachineInfo1.Machine_Site
    '                UPdataByReal.Plant = MachineInfo1.Machine_Plant   '厂别
    '                UPdataByReal.Dept = MachineInfo1.Machine_Dept    '车间
    '                UPdataByReal.Line = MachineInfo1.Machine_LineID  '线别
    '                UPdataByReal.MachineName = MachineInfo1.Machine_MName   '设备名
    '                UPdataByReal.MachineModel = MachineInfo1.Machine_MModel  '设备型号
    '                UPdataByReal.MachineSN = MachineInfo1.Machine_MSN '设备SN
    '                UPdataByReal.MachineNO = MachineInfo1.Machine_MNO '设备NO
    '                UPdataByReal.MachineIP = MachineInfo1.Machine_MIP '设备IP
    '                UPdataByReal.evt_dt = 0 'epoch time
    '                UPdataByReal.Model = DataByReal.Model  'Model name,Init Pro中赋值
    '                UPdataByReal.Program = DataByReal.Program 'program name,Init Pro中赋值
    '                UPdataByReal.Status = DataByReal.Status '状态,FrmLoad时=ON,退出时=OFF,机器人赋值IDLE/Run/Shutdown
    '                UPdataByReal.Errcode = DataByReal.Errcode  'Machine Error Code,异常code

    '                'DataByReal = NullDataByReal
    '                Dim jsonHelper As JsonHelper = New JsonHelper
    '                Dim ss1 As String = jsonHelper.ToJson(UPdataByReal)
    '                Dim ss As String = ""
    '                Dim saveName As String = DataPath & "BYREAL" & Format(DateTime.Now, "-yyyyMMdd-Hmmss-ffff") & ".json"
    '                Dim WM_SETFOCUS As IntPtr = &H7
    '                Dim WM_SETTEXT As IntPtr = &HC
    '                Dim lngCalculator As IntPtr = FindWindow(vbNullString, "数据上传")
    '                Dim Line As IntPtr = FindWindowEx(lngCalculator, 0, vbNullString, "BYREAL")

    '                '数据上传
    '                If ss1 <> OldDataByReal Or UPloadTime > 300 Then '状态变化 or 每5min上传
    '                    UPloadTime = 0
    '                    UPdataByReal.evt_dt = timeNow 'epoch time
    '                    ss = jsonHelper.ToJson(UPdataByReal)
    '                    Dim Pwrite As New System.IO.StreamWriter(saveName)
    '                    Pwrite.Write(ss)
    '                    Pwrite.Close()

    '                    Dim i As Integer = SendMessage(Line, WM_SETTEXT, 0, saveName)
    '                    If i = 0 Then
    '                        If TextBox8_UpLoadStatus.BackColor <> Color.Red Then
    '                            AppendInfoToTextBox("数据上传程序已断开!")
    '                            TextBox8_UpLoadStatus.BackColor = Color.Red
    '                            TextBox8_UpLoadStatus.Text = "关闭"
    '                        End If
    '                    Else
    '                        TextBox8_UpLoadStatus.BackColor = Color.Lime
    '                        TextBox8_UpLoadStatus.Text = "开启"
    '                    End If
    '                End If
    '                OldDataByReal = ss1

    '                Dim Line2 As IntPtr = FindWindowEx(lngCalculator, 0, vbNullString, "Status")
    '                Dim j As Integer = SendMessage(Line2, WM_SETTEXT, 0, "已开启")
    '                '数据上传状态
    '                If j = 0 Then
    '                    If TextBox8_UpLoadStatus.BackColor <> Color.Red Then
    '                        AppendInfoToTextBox("数据上传程序已断开!")
    '                        TextBox8_UpLoadStatus.BackColor = Color.Red
    '                        TextBox8_UpLoadStatus.Text = "关闭"
    '                    End If
    '                Else
    '                    TextBox8_UpLoadStatus.BackColor = Color.Lime
    '                    TextBox8_UpLoadStatus.Text = "开启"
    '                End If

    '            Else    '初始化未完成
    '                GoTo d
    '            End If

    '            If UPdataByReal.Status = "Off" Then
    '                UpLoadComplete_flag = True
    '            End If

    '            '运行状态"ON/OFF/IDLE/Run/Shutdown"
    '            If DataByReal.Status = "Shutdown" Or DataByReal.Status = "Off" Then
    '                TextBox_RunStatus.Text = "Shutdown"
    '                TextBox_RunStatus.BackColor = Color.Red
    '            ElseIf DataByReal.Status = "Idle" Then
    '                TextBox_RunStatus.Text = "Idle"
    '                TextBox_RunStatus.BackColor = Color.Yellow
    '            ElseIf DataByReal.Status = "Run" Or DataByReal.Status = "On" Then
    '                TextBox_RunStatus.Text = "Run"
    '                TextBox_RunStatus.BackColor = Color.Lime
    '            End If

    '            'ErrCode
    '            If DataByReal.Errcode = "" Then
    '                ErrorCode.Text = "NA"
    '                ErrorCode.ForeColor = Color.Black
    '            Else
    '                ErrorCode.Text = DataByReal.Errcode
    '                ErrorCode.ForeColor = Color.Red
    '            End If
    '            'OP ID
    '            If gPriority = 0 Then
    '                TextBox_OPID.Text = "未登录"
    '                TextBox_OPID.BackColor = Color.WhiteSmoke
    '            Else
    '                TextBox_OPID.Text = DataByPCS.OperatorID
    '                TextBox_OPID.BackColor = Color.Lime
    '            End If

    'd:
    '        Catch ex As Exception
    '            UploadStatus.Enabled = False
    '            AppendInfoToTextBox(ex.Message.ToString & ex.StackTrace.ToString)
    '        End Try
    '    End Sub
    ''' <summary>
    ''' 判断当前产品栏下拉框中是否有该产品
    ''' </summary>
    ''' <param name="s"></param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Private Function ProIsExists(ByVal s As String) As Boolean
        Try
            For i As Integer = 0 To TCmbPro.Items.Count - 1
                If TCmbPro.Items(i) = UCase(s) Then
                    Return True
                End If
            Next
            Return False
        Catch ex As Exception
            MsgBox("ProIsExists:" & ex.Message.ToString & ex.StackTrace.ToString)
        End Try

    End Function

    ''' <summary>
    ''' 改变当前产品栏下拉框中选中的产品
    ''' </summary>
    ''' <param name="s"></param>
    ''' <remarks></remarks>
    Private Sub ChangePro(ByVal s As String)
        Try
            If ProIsExists(UCase(s)) Then
                TCmbPro.SelectedItem = UCase(s)
            Else
                TCmbPro.Items.Add(UCase(s))
                TCmbPro.SelectedItem = UCase(s)
            End If
        Catch ex As Exception
            MsgBox("ChangePro:" & ex.Message.ToString & ex.StackTrace.ToString)
        End Try

    End Sub

    ''' <summary>
    ''' 压缩图片保存到指定文件夹下
    ''' </summary>
    ''' <param name="CogRecordDisplay"></param>
    ''' <param name="tmpfifo0"></param>
    ''' <param name="PicPath"></param>
    ''' <param name="PicName"></param>
    ''' <remarks></remarks>
    Private Sub YSPic(ByVal CogRecordDisplay As Cognex.VisionPro.CogRecordDisplay, ByVal tmpfifo0 As CogIPOneImageTool, ByVal PicPath As String, ByVal PicName As String)
        Try
            CogRecordDisplay.Image = tmpfifo0.OutputImage
            Dim codecs() As ImageCodecInfo = ImageCodecInfo.GetImageEncoders()
            Dim ici As ImageCodecInfo = Nothing
            Dim codec As ImageCodecInfo
            Dim compressPic1 As New Bitmap(CogRecordDisplay.Image.ToBitmap())
            Dim compressPic As Bitmap = New Bitmap(compressPic1)
            compressPic1.Dispose()
            Dim ep As EncoderParameters = New EncoderParameters()
            For Each codec In codecs
                If (codec.MimeType = "image/jpeg") Then
                    ici = codec
                End If
            Next
            '此处参数85代表压缩率，建议设置65-85之间， 范围0-100 ， 100代表图片质量最优，但压缩率最低
            ep.Param(0) = New EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 85)
            If Directory.Exists(PicPath) = False Then  '判断文件夹是否存在
                Directory.CreateDirectory(PicPath)
            End If
            compressPic.Save(PicPath & PicName, ici, ep)
            compressPic.Dispose()
        Catch ex As Exception
            MsgBox("YSPic:" & ex.Message.ToString & ex.StackTrace.ToString)
        End Try

    End Sub

    ''' <summary>
    ''' 清理指定路径下的文件夹，且只保留前七个文件夹
    ''' </summary>
    ''' <param name="path"></param>
    ''' <remarks></remarks>
    Private Sub DeleteDir(ByVal path As String)
        Try
            Dim deletePath1 As String = DebugPath & "\SFCSData\DataByPCS\"
            Dim deletePath2 As String = DebugPath & "\SFCSData\DataByReal\"
            Dim fileExits0 As New DirectoryInfo(path)
            Dim fileExits1 As New DirectoryInfo(deletePath1)
            Dim fileExits2 As New DirectoryInfo(deletePath2)

            'If fileExits1.Exists = True Then
            '    Dim fileList() As String = Directory.GetDirectories(deletePath1)
            '    If fileList.Length > 7 Then
            '        For i As Integer = 1 To fileList.Length - 7
            '            Directory.Delete(fileList(i - 1), True)
            '        Next
            '        AppendInfoToTextBox("Delete ByPCS Data!")
            '    End If
            'End If

            'If fileExits2.Exists = True Then
            '    Dim fileList() As String = Directory.GetDirectories(deletePath2)
            '    If fileList.Length > 7 Then
            '        For i As Integer = 1 To fileList.Length - 7
            '            Directory.Delete(fileList(i - 1), True)
            '        Next
            '        AppendInfoToTextBox("Delete ByReal Data!")
            '    End If
            'End If
            If fileExits0.Exists Then
                Dim ss() As String = path.Split("\")
                If ss(ss.Length - 2) = "VisionFailed" Then
                    Dim fileList() As String = Directory.GetDirectories(path)
                    If fileList.Length > 7 Then
                        For i As Integer = 1 To fileList.Length - 7
                            Directory.Delete(fileList(i - 1), True)
                        Next
                        AppendInfoToTextBox("Delete failed Picture!")
                    End If
                End If
            End If
        Catch ex As Exception
            MsgBox("DeleteDir:" & ex.Message.ToString & ex.StackTrace.ToString)
        End Try

    End Sub

    ''' <summary>
    ''' 以json格式写入文档
    ''' </summary>
    ''' <param name="obj"></param>
    ''' <param name="FileName "></param>
    ''' <remarks></remarks>
    Private Sub SaveJsonToFile(ByVal obj As Object, ByVal FileName As String)
        Dim DataPath As String = DebugPath & "\SFCSData\DataByPCS\"
        Try
            If Directory.Exists(DataPath) = False Then  '判断文件夹是否存在
                Directory.CreateDirectory(DataPath)
            End If
            Dim jsonHelper As JsonHelper = New JsonHelper
            Dim s As String = jsonHelper.ToJson(obj)
            Dim Pwrite As New System.IO.StreamWriter(DataPath & FileName & ".json")
            Pwrite.WriteLine(s)
            Pwrite.Close()
        Catch ex As Exception
            MsgBox(ex.Message.ToString)
        End Try
    End Sub

    ' ''' <summary>
    ' ''' 打开程序
    ' ''' </summary>
    ' ''' <remarks></remarks>
    'Private Sub OpenUploadProcess()
    '    Try
    '        Dim a As Integer
    '        a = Shell(UploadPath & "\Upload.exe", vbNormalFocus)
    '        If a = 0 Then
    '            MsgBox("数据上传程序打开失败！！")
    '        End If
    '        If ResultShow_flag = True Then
    '            Dim b As Integer
    '            b = Shell(DebugPath & "\锁附结果显示\ResultShow.exe", vbNormalFocus)
    '        End If

    '    Catch ex As Exception
    '        MsgBox("OpenUploadProcess:" & ex.Message.ToString & ex.StackTrace.ToString)
    '    End Try

    'End Sub
    ' ''' <summary>
    ' ''' 关闭数据上传程序
    ' ''' </summary>
    ' ''' <remarks></remarks>
    'Private Sub CloseUploadProcess()
    '    Try
    '        Dim winHwnd1 As IntPtr = FindWindow(vbNullString, "锁附结果显示")
    '        Dim RetVal1 As IntPtr
    '        If winHwnd1 <> 0 Then
    '            RetVal1 = PostMessage(winHwnd1, WM_CLOSE, 0&, 0&)
    '        End If

    '        Dim winHwnd As IntPtr = FindWindow(vbNullString, "数据上传")
    '        Dim RetVal As IntPtr
    '        If winHwnd <> 0 Then
    '            RetVal = PostMessage(winHwnd, WM_CLOSE, 0&, 0&)
    '        End If
    '    Catch ex As Exception
    '        MsgBox("CloseUploadProcess:" & ex.Message.ToString & ex.StackTrace.ToString)
    '    End Try

    'End Sub

    ''' <summary>
    ''' Z相脉冲检测程序
    ''' </summary>
    ''' <remarks></remarks>
    'Private Function ZaxisCheck(ByVal AxActUtlType1 As AxActUtlTypeLib.AxActUtlType, ByVal pointNO As Integer)
    '    Dim szDevice As String = "D800"   'DeviceName'
    '    Dim IData(2) As Integer      'Z项脉冲计数
    '    Dim ISize As Integer = 1
    '    Dim IRet As Integer
    '    Dim result As Boolean = False
    '    Try
    '        IRet = AxActUtlType1.ReadDeviceRandom(szDevice, ISize, IData(0))
    '        AppendInfoToTextBox("第" & pointNO & "颗锁附圈数:" & IData(0))
    '        AppendInfoToTextBox("第" & pointNO & "颗设定圈数:" & ZaxisPls(pointNO))
    '        If Abs(IData(0) - ZaxisPls(pointNO)) <= ZaxisPls(0) Then    '反馈圈数与设定圈数差
    '            result = True
    '        Else
    '            result = False
    '        End If

    '    Catch ex As Exception
    '        AppendInfoToTextBox(ex.Message.ToString)
    '    End Try

    '    Return result
    'End Function
    ' ''' <summary>
    ' ''' 螺丝起枪使用次数检测程序
    ' ''' </summary>
    ' ''' <remarks></remarks>
    'Private Sub GunTimesCheck(ByVal AxActUtlType1 As AxActUtlTypeLib.AxActUtlType)
    '    Dim szDevice1 As String = "D896"   '设定次数DeviceName'
    '    Dim szDevice2 As String = "D892"   '使用次数DeviceName'
    '    Dim IData1(2) As Long      '设定次数
    '    Dim IData2(2) As Long      '已用次数
    '    Dim setTimes As Double
    '    Dim useTimes As Double
    '    Dim H1, H2 As Long
    '    Dim L1, L2 As Long
    '    Dim ISize As Integer = 1
    '    Dim IRet As Integer
    '    Dim result As Boolean = False
    '    Try
    '        IRet = AxActUtlType1.ReadDeviceRandom("D896", ISize, IData1(0))
    '        L1 = IData1(0)
    '        IRet = AxActUtlType1.ReadDeviceRandom("D897", ISize, IData1(0))
    '        H1 = IData1(0)

    '        setTimes = H1 * 65536 + L1

    '        IRet = AxActUtlType1.ReadDeviceRandom("D892", ISize, IData2(0))
    '        L2 = IData2(0)
    '        IRet = AxActUtlType1.ReadDeviceRandom("D893", ISize, IData2(0))
    '        H2 = IData2(0)

    '        useTimes = H2 * 65536 + L2

    '        AppendInfoToTextBox("settimes:" & setTimes)
    '        AppendInfoToTextBox("usetimes:" & useTimes)
    '        If setTimes > 0 Then
    '            If (useTimes / setTimes) > 0.8 Then '次数达到
    '                AppendInfoToTextBox("枪头使用次数到达!")
    '            End If
    '        Else
    '            AppendInfoToTextBox("枪头次数未设置或错误!")
    '        End If

    '    Catch ex As Exception
    '        AppendInfoToTextBox(ex.Message.ToString)
    '    End Try
    'End Sub

    Private Sub 屏幕键盘ToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles 屏幕键盘ToolStripMenuItem.Click
        System.Diagnostics.Process.Start("C:\WINDOWS\system32\osk.exe")
    End Sub

    Private Sub 截图工具ToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles 截图工具ToolStripMenuItem.Click
        System.Diagnostics.Process.Start("C:\WINDOWS\system32\SnippingTool.exe")
    End Sub

    Private Sub 上传程序ToolStripMenuItem_Click(sender As Object, e As EventArgs)
        FrmUpLoadPrg.ShowDialog()
    End Sub

    ''' <summary>
    ''' 视觉识败图片存放路径判断
    ''' </summary>
    ''' <remarks></remarks>
    Private Sub CheckVisionfailedPath()
        Dim ss() As String = gVisionFailedPath.Split("\")
        If System.IO.Directory.Exists(gVisionFailedPath) = False Then
            MsgBox("视觉失败图片存放路径不存，请指定或建立！")
            FrmVisionFailPath.ShowDialog()
        End If
        If ss(ss.Length - 2) <> "VisionFailed" Then
            MsgBox("视觉失败图片存放路径未指向VisionFailed文件夹，请指定或建立！")
            FrmVisionFailPath.ShowDialog()
        End If
    End Sub

    Private Sub 锁附点模板ToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles 锁附点模板ToolStripMenuItem.Click
        ' FormFailPoint.ShowDialog()
        Try
            If ResultShow_flag = True Then
                Dim picshow As New LNLONPIC.Frm_PointSelect
                picshow.Run(Chanpin, DebugPath, CurScrewPara.PointCount)
            Else
                MsgBox("该功能未开启！" & vbCrLf & "请在 设置-参数设置-系统设置 中将'锁附结果显示'功能开启！")
            End If
        Catch ex As Exception
            MsgBox(ex.Message.ToString)
        End Try
    End Sub

    ''' <summary>
    ''' 初始化产品模板图片
    ''' </summary>
    ''' <param name="name"></param>
    ''' <remarks></remarks>
    '    Private Sub initPointModel(ByVal name As String)
    '        GoTo D
    '        Try

    '            Dim file_num As Integer = FreeFile()
    '            Dim pointFilePath As String = DebugPath & "\Tool\" & name & "\" & name & "模板点位.txt"
    '            Dim OpenPointFile As Boolean = Exists(pointFilePath)
    '            If OpenPointFile = True Then
    '                FileOpen(file_num, pointFilePath, OpenMode.Random)
    '                Dim n As Integer = 1
    '                Do While Not EOF(file_num)
    '                    FileGet(file_num, CurPointMark(n))
    '                    n += 1
    '                Loop
    '                FileClose(file_num)
    '                If CurScrewPara.PointCount <> n - 2 Then
    '                    AppendInfoToTextBox("螺丝颗数不一致！")
    '                    TextBox_Info.Text = "螺丝颗数与选点数不一致:" & CurScrewPara.PointCount
    '                    showFailPoint = False
    '                Else
    '                    showFailPoint = True
    '                End If
    '            End If

    '            Dim OpenPointPIC As Boolean = Exists(DebugPath & "\Tool\" & name & "\" & name & ".jpg")
    '            If OpenPointPIC = True Then
    '                PictureBox6.Image = Image.FromFile(DebugPath & "\Tool\" & name & "\" & name & ".jpg")
    '                TextBox_Info.Text = ""
    '            Else
    '                PictureBox6.Image = New Bitmap(PictureBox6.Width, PictureBox6.Height)
    '                TextBox_Info.Text = "未找到" & name & "的图片!"
    '            End If

    '        Catch ex As Exception
    '            AppendInfoToTextBox("InitFailPoint:" & ex.Message.ToString)
    '        End Try
    'D:
    '    End Sub
    Private Sub PointResultShow(ByVal Result As String, ByVal curNo As Integer)
        If ResultShow_flag = False Then
            GoTo D
        End If

        Try
            If curNo > CurScrewPara.PointCount Then
                GoTo D
            End If
            Dim ResultShow As LNLONPIC.DrawOnImage = New LNLONPIC.DrawOnImage
            CurPointMark(curNo).PointResult = Result
            ' PictureBox6.Image = ResultShow.DrawMark(PictureBox6, PictureBox6.Image, CurPointMark(curNo), curNo)

            Dim OK_count As Integer
            Dim NG_count As Integer
            Dim Skip_count As Integer
            For i = 1 To curNo
                If CurPointMark(i).PointResult = "OK" Then
                    OK_count += 1
                ElseIf CurPointMark(i).PointResult = "NG" Then
                    NG_count += 1
                ElseIf CurPointMark(i).PointResult = "skip" Then
                    Skip_count += 1
                End If
            Next
            'TextBox_Info.Text = "锁附OK数:" & OK_count & ";锁附NG数:" & NG_count & ";漏锁数:" & Skip_count
        Catch ex As Exception
            AppendInfoToTextBox("FailPointShow:" & ex.Message.ToString)
        End Try
D:
    End Sub

    Private Sub WriteMark(ByVal pMark As Point_Mark, ByVal r As Integer, ByVal NO As Integer)
        Dim PointColor As Color
        Dim PointBrushes As Brush
        If pMark.PointResult = "OK" Then
            '锁附ok
            PointColor = Color.Green
            PointBrushes = Brushes.Green
        ElseIf pMark.PointResult = "NG" Then
            '锁附ng
            PointColor = Color.Red
            PointBrushes = Brushes.Red
        Else
            '漏锁
            PointColor = Color.Gray
            PointBrushes = Brushes.Gray
        End If

        Try
            '   Dim myGraphics As Graphics = Me.PictureBox6.CreateGraphics  '声明并创建一个Graphics对象
            Dim myPen As Pen = New Pen(PointColor, 1) '声明一个画笔，并设定颜色和粗细
            myPen.DashStyle = Drawing.Drawing2D.DashStyle.Solid '线型，Solid是实线
            '画圆
            Dim rect As Rectangle = New Rectangle(pMark.PointX - r / 2, pMark.PointY - r / 2, r, r)
            myGraphics.DrawEllipse(myPen, rect)
            myGraphics.FillEllipse(PointBrushes, rect)
            '填充
            Dim mBrush As New SolidBrush(Drawing.Color.Black)
            Dim mFont As New Font("微软雅黑", 10 * picRatio)
            myGraphics.DrawString(NO.ToString, mFont, mBrush, pMark.PointX - r / 2, pMark.PointY - r / 2)

            '   myGraphics.Dispose() '释放Graphics占用的资源
        Catch ex As Exception
            MsgBox(ex.Message.ToString)
        End Try
    End Sub

    'Private Function Ratio_Image(ByVal X As Integer, ByVal Y As Integer, ByVal myPoint As Point_Mark)
    '    Try
    '        Dim r As Double
    '        Dim ratio As Double
    '        Dim re_Point As Point_Mark = myPoint
    '        r = (PictureBox6.Width * Y) / (PictureBox6.Height * X)
    '        Select Case r
    '            Case 1  '宽高等比
    '                ratio = X / PictureBox6.Width
    '                re_Point.PointX = myPoint.PointX * ratio
    '                re_Point.PointY = myPoint.PointY * ratio
    '            Case Is < 1 'width 基准
    '                ratio = X / PictureBox6.Width
    '                re_Point.PointX = myPoint.PointX * ratio
    '                re_Point.PointY = (myPoint.PointY * ratio - (PictureBox6.Height * ratio - Y) / 2)

    '            Case Is > 1 'height 基准
    '                ratio = Y / PictureBox6.Height
    '                re_Point.PointX = (myPoint.PointX * ratio - (PictureBox6.Width * ratio - X) / 2)
    '                re_Point.PointY = myPoint.PointY * ratio
    '        End Select
    '        picRatio = ratio
    '        Return re_Point
    '    Catch ex As Exception
    '        MsgBox(ex.Message.ToString)
    '    End Try
    'End Function

    Private Sub Button1_Click(sender As Object, e As EventArgs)
        Try
            If ResultShow_flag = True Then
                Dim b As Integer
                b = Shell(DebugPath & "\锁附结果显示\ResultShow.exe", vbNormalFocus)
            Else
                MsgBox("该功能未开启！" & vbCrLf & "请在 设置-参数设置-系统设置 中将'锁附结果显示'功能开启！")

            End If
        Catch ex As Exception

        End Try
    End Sub

    ''' <summary>
    ''' '保存锁附结果图片
    ''' </summary>
    ''' <remarks></remarks>
    Private Sub SavePointResultPIC()
        If ResultShow_flag = False Then '禁用
            GoTo d
        End If
        Try

            Dim tNow As String = Format(DateTime.Now, "yyyyMMdd_hhmmss")
            Dim fileName As String = ""
            If CurNameAndSN.ChanpinSN = "" Then
                fileName = tNow & "_" & "NULL" & "_" & Chanpin & ".jpg"
            Else
                fileName = tNow & "_" & CurNameAndSN.ChanpinSN & "_" & Chanpin & ".jpg"
            End If
            Dim PointResultPath As String = "C:\ResultPic\" & fileName
            AppendInfoToTextBox(vbCrLf & "SavePointResultPIC" & vbCrLf)
            If Directory.Exists("C:\ResultPic") = False Then
                Directory.CreateDirectory("C:\ResultPic")
            End If
            'PictureBox6.Image.Save(PointResultPath)

            '发送结果到显示程序
            Dim WM_SETFOCUS As IntPtr = &H7
            Dim WM_SETTEXT As IntPtr = &HC
            Dim lngCalculator As IntPtr = FindWindow(vbNullString, "锁附结果显示")
            Dim Line As IntPtr = FindWindowEx(lngCalculator, 0, vbNullString, "Info")
            Dim j As Integer = SendMessage(Line, WM_SETTEXT, 0, PointResultPath)
            If j = 0 Then
                AppendInfoToTextBox("锁附结果显示程序已断开")
            End If

            '发送信息到显示程序
            'Dim ResultMessage As String
            'If DataByPCS.IsOK = 1 Then
            '    ResultMessage = "OK;" & TextBox_Info.Text
            'Else
            '    ResultMessage = "NG;" & TextBox_Info.Text
            'End If
            'Dim Line2 As IntPtr = FindWindowEx(lngCalculator, 0, vbNullString, "RESULT")
            'Dim j2 As Integer = SendMessage(Line2, WM_SETTEXT, 0, ResultMessage)
            'If j2 = 0 Then
            '    AppendInfoToTextBox("锁附结果显示程序已断开")
            'End If
        Catch ex As Exception
            AppendInfoToTextBox("SavePointResultPIC:" & ex.Message.ToString & vbCrLf)
        End Try
d:
    End Sub

    ''' <summary>
    ''' 开机延时
    ''' </summary>
    ''' <remarks></remarks>
    Private Sub StartDly()
        '
        Try
            '开机延时
            Dim openSTARTDLY As Boolean = Exists(DebugPath & "\Tool\StartDlyTime.txt")
            If openSTARTDLY = True Then
                Dim startDly_num As Integer = FreeFile()
                FileOpen(startDly_num, DebugPath & "\Tool\StartDlyTime.txt", OpenMode.Random)
                FileGet(startDly_num, StartDlyTime)
                FileGet(startDly_num, IDLETime)
                FileClose(startDly_num)
            Else
                StartDlyTime = 120
                IDLETime = 3000
            End If
            '
            Dim startTime As DateTime = DateTime.Now.AddMilliseconds(-(Environment.TickCount))
reWait:
            Dim timeNow As DateTime = DateTime.Now
            Dim Waitseconds As Long = DateDiff(DateInterval.Second, startTime, timeNow) 'DateInterval.seconds：精确到秒
            If Waitseconds < StartDlyTime Then
                AppendInfoToTextBox("开机等待：" & (StartDlyTime - Waitseconds) & "s")
                waitstandby(1000)
                GoTo reWait
            End If
        Catch ex As Exception
            StartDlyTime = 120
            IDLETime = 3000
        End Try
    End Sub

    Public Sub photoToRobot(ByRef MySocket As Socket, ByVal StrReceData As String)
        Try
            '从数据库中读取拍照点坐标
            Dim sql As String = "select * from photo_point where Product='" & Chanpin & "'" '产品表单模板名字'产品表单模板名字"
            ' da = New OleDbDataAdapter(sql, cn)
            ds = New DataSet
            ds = SearchMysql(sql)

            For w = 0 To 2
                Dim m As Integer = 4 * w
                photo_point(m) = Val(ds.Tables(0).Rows(w)(2))
                photo_point(m + 1) = Val(ds.Tables(0).Rows(w)(3))
                photo_point(m + 2) = Val(ds.Tables(0).Rows(w)(4))
                photo_point(m + 3) = Val(ds.Tables(0).Rows(w)(5))
            Next
            '''''''''拍照点平移量添加
            If PhotoPY_flag = True Then
                photo_point(1) = photo_point(1) + Val(PhotoPY)
                photo_point(5) = photo_point(5) + Val(PhotoPY)
                photo_point(9) = photo_point(9) + Val(PhotoPY)
            End If
            '将拍照点发送至机器人
            Dim strSendData As String = ""
            strSendData = ""
            strSendData = Format(photo_point(0), "0.000") + "," + Format(photo_point(1), "0.000") + "," + Format(photo_point(2), "0.000") + "," + Format(photo_point(3), "0.000") + ","
            strSendData += Format(photo_point(4), "0.000") + "," + Format(photo_point(5), "0.000") + "," + Format(photo_point(6), "0.000") + "," + Format(photo_point(7), "0.000") + ","
            strSendData += Format(photo_point(8), "0.000") + "," + Format(photo_point(9), "0.000") + "," + Format(photo_point(10), "0.000") + "," + Format(photo_point(11), "0.000") + ","
            strSendData += CStr(suofu_Mod) + "," + CStr(Online_Mod)
            AppendInfoToTextBox("send:x: " + strSendData + vbCrLf)

            Dim i As Integer = 0
            strSendData += vbCrLf
            Dim byteSend As Byte() = Encoding.ASCII.GetBytes(strSendData)
            MySocket.Send(byteSend)
        Catch ex As Exception
            MsgBox("photoToRobot:" & ex.Message.ToString)
        End Try

    End Sub

    ''' <summary>
    ''' 加载扭力角度供料器等参数
    ''' </summary>
    ''' <remarks></remarks>
    Private Sub GetPointPara()
        Dim i As Integer = 0
        Try
            Dim DBpath As String = DebugPath & "\Tool\" & TCmbPro.Text & "\PointPara.accdb"
            Dim sql As String = "select * from PointPara where Product='" & TCmbPro.Text & "'"
            Dim pointData As DataSet = New DataSet
            pointData = SearchMysql(sql)

            If File.Exists(DBpath) = False Then '没有文件,直接跳过

                For i = 0 To 3
                    GetPass(i).X = 0
                    GetPass(i).Y = 0
                    GetPass(i).Z = 0
                    GetPass(i).C = 0
                    SetPass(i).X = 0
                    SetPass(i).Y = 0
                    SetPass(i).Z = 0
                    SetPass(i).C = 0
                Next
                For i = 1 To 30

                    PointPass(i).X = 1 'ARCH
                    PointPass(i).Y = 0 'GET
                    PointPass(i).Z = 0 'SET
                Next

                GoTo d
            End If

            '读取锁附参数

            For i = 1 To 30
                PointPara(i).torque = pointData.Tables(0).Rows(i - 1)(2)
                PointPara(i).angle = pointData.Tables(0).Rows(i - 1)(3)
                PointPara(i).feeder = pointData.Tables(0).Rows(i - 1)(4)
                PointPara(i).diable = pointData.Tables(0).Rows(i - 1)(5)

                PointPass(i).X = pointData.Tables(0).Rows(i - 1)(6) 'ARCH
                PointPass(i).Y = pointData.Tables(0).Rows(i - 1)(7) 'GET
                PointPass(i).Z = pointData.Tables(0).Rows(i - 1)(8) 'SET
            Next

            '读取Arch
            sql = "select * from ArchPara where Product='" & TCmbPro.Text & "'"
            'cnStr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & DBpath & ";Persist Security Info=False;Jet OLEDB:Database Password='1234'"
            Dim readData As DataSet = New DataSet
            readData = SearchMysql(sql)
            For i = 0 To 3
                Arch(i).X = readData.Tables(0).Rows(i)(2)
                Arch(i).Y = readData.Tables(0).Rows(i)(3)
                Arch(i).Z = readData.Tables(0).Rows(i)(4)
                Arch(i).A = readData.Tables(0).Rows(i)(5)
            Next

            '读取Timer
            sql = "select * from TimerDelay where Product='" & TCmbPro.Text & "'"
            'cnStr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & DBpath & ";Persist Security Info=False;Jet OLEDB:Database Password='1234'"
            readData = SearchMysql(sql)
            For i = 0 To 2
                TimerDelay(i) = readData.Tables(0).Rows(i)(2)
            Next

            '读取避障设置
            sql = "select * from PassSet where Product='" & TCmbPro.Text & "'"
            'cnStr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & DBpath & ";Persist Security Info=False;Jet OLEDB:Database Password='1234'"
            readData = SearchMysql(sql)
            For i = 0 To 3
                GetPass(i).X = readData.Tables(0).Rows(i)(2)
                GetPass(i).Y = readData.Tables(0).Rows(i)(3)
                GetPass(i).Z = readData.Tables(0).Rows(i)(4)
                GetPass(i).C = readData.Tables(0).Rows(i)(5)
            Next
            For i = 0 To 3
                SetPass(i).X = readData.Tables(0).Rows(i + 4)(2)
                SetPass(i).Y = readData.Tables(0).Rows(i + 4)(3)
                SetPass(i).Z = readData.Tables(0).Rows(i + 4)(4)
                SetPass(i).C = readData.Tables(0).Rows(i + 4)(5)
            Next
d:
        Catch ex As Exception
            MsgBox("GetPointPara err:" & ex.Message.ToString)
        End Try
    End Sub

    'Private Sub Button5_Click(sender As Object, e As EventArgs)
    '    If Button_show.Text = "示教" Then
    '        Button_show.Text = "未启用"
    '        Button_show.BackColor = Color.WhiteSmoke
    '        Button_show.UseVisualStyleBackColor = True

    '    Else
    '        Button_show.Text = "示教"
    '        Button_show.BackColor = Color.Lime

    '    End If
    'End Sub
    ''' <summary>
    ''' 发送点位扭力,角度,供料器,skip_flag 参数
    ''' </summary>
    ''' <param name="MySocket"></param>
    ''' <param name="StrReceData"></param>
    ''' <remarks></remarks>
    Private Sub SendPointPara(ByRef MySocket As Socket, ByVal StrReceData As String)
        Try
            Dim Strdata As String = ""
            Dim Strdata1 As String = ""
            Dim Pangle(30) As Double
            Dim i, j As Integer
            'Dim diable1(15) As Integer
            If Val(CurScrewPara.PointCount) < Val(KESU) And Photo3_flag = True Then
                j = Val(KESU)
            Else
                j = Val(CurScrewPara.PointCount)
            End If

            For i = 1 To j
                Strdata = Format(PointPara(i).torque, "0.00") + "," + Format(PointPara(i).feeder, "0.00") + "," + CStr(PointPara(i).diable) + "," + Format(PointPara(i).angle, "0.00")
                Dim byteSend As Byte() = Encoding.ASCII.GetBytes(Strdata + vbCrLf)
                AppendInfoToTextBox("send:" + Strdata + vbCrLf)
                MySocket.Send(byteSend)
            Next
            Globalfunc.waitstandby(50)
        Catch ex As Exception
            AppendInfoToTextBox("Err in SendPointPara:" & ex.Message.ToString & ex.StackTrace.ToString)
        End Try
    End Sub

    ''' <summary>
    ''' 发送点位扭力,角度,供料器,skip_flag 参数
    ''' </summary>
    ''' <param name="MySocket"></param>
    ''' <param name="StrReceData"></param>
    ''' <remarks></remarks>
    Private Sub SendPointPara2(ByRef MySocket As Socket, ByVal StrReceData As String)
        Dim Strdata As String
        Dim byteSend As Byte()
        Dim i, j As Integer
        Try
            If StrReceData = "2" Then
                '发送Arch设定值
                GoTo Two
            ElseIf StrReceData = "3" Then
                '发送避障路径设定值
                GoTo Three
            ElseIf StrReceData = "4" Then
                '发送螺丝选定参数
                GoTo Four
            Else
                GoTo D
            End If
Two:
            Strdata = ""
            'Strdata &= Arch(0).PtoString & "," & Arch(1).PtoString & "," & Arch(2).PtoString & "," & Arch(3).PtoString & ","
            Strdata = Format(TimerDelay(0), "0.00") & "," & Format(TimerDelay(1), "0.00") & "," & Format(TimerDelay(2), "0.00")
            byteSend = Encoding.ASCII.GetBytes(Strdata + vbCrLf)
            AppendInfoToTextBox("send2:" + Strdata + vbCrLf)
            MySocket.Send(byteSend)
            GoTo D
Three:

            Strdata = ""
            For i = 0 To 3
                Strdata = Format(GetPass(i).X, "0.00") + "," + Format(GetPass(i).Y, "0.00") + "," + Format(GetPass(i).Z, "0.00") + "," + Format(GetPass(i).C, "0.00") + ","
                Strdata += Format(SetPass(i).X, "0.00") + "," + Format(SetPass(i).Y, "0.00") + "," + Format(SetPass(i).Z, "0.00") + "," + Format(SetPass(i).C, "0.00") + ","
                byteSend = Encoding.ASCII.GetBytes(Strdata + vbCrLf)
                AppendInfoToTextBox("send3:" + Strdata + vbCrLf)
                MySocket.Send(byteSend)
            Next
            GoTo D
Four:
            If Val(CurScrewPara.PointCount) < Val(KESU) And Photo3_flag = True Then
                j = Val(KESU)
            Else
                j = Val(CurScrewPara.PointCount)
            End If
            Strdata = ""
            For i = 1 To j
                Strdata = PointPass(i).X.ToString + "," + PointPass(i).Y.ToString + "," + PointPass(i).Z.ToString
                byteSend = Encoding.ASCII.GetBytes(Strdata + vbCrLf)
                AppendInfoToTextBox("send4:" + Strdata + vbCrLf)
                MySocket.Send(byteSend)
                waitstandby(100)
            Next

D:
        Catch ex As Exception
            AppendInfoToTextBox("Err in SendPointPara:" & ex.Message.ToString & ex.StackTrace.ToString)
        End Try
    End Sub

    Private Sub Button_Robot_Click(sender As Object, e As EventArgs)
        If RobotPanel_flag = False Then '禁用
            MsgBox("该功能未开启！" & vbCrLf & "请在 设置-参数设置-系统设置 中将'机器人面板'功能开启！")
            GoTo d
        End If

        Dim robotpath As String = DebugPath & "\RT"

        Try
            '写地址
            File.WriteAllText(robotpath & "\pointPath.txt", DebugPath & "\Tool\" & TCmbPro.Text)
            '开启机器人软件
            Dim a As Integer
            a = Shell(robotpath & "\RT.exe", vbNormalFocus)
            If a = 0 Then
                MsgBox("机器人程序打开失败！！")
            End If
        Catch ex As Exception
            MsgBox("OpenUploadProcess:" & ex.Message.ToString & ex.StackTrace.ToString)
        End Try
d:
    End Sub

    Private Sub 新增产品向导ToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles 新增产品向导ToolStripMenuItem.Click
        If Guide_flag = False Then '禁用
            MsgBox("该功能未开启！" & vbCrLf & "请在 设置-参数设置-系统设置 中将'新建产品向导'功能开启！")
        Else
            FrmAddProd2.Show()
        End If

    End Sub

    Private Sub P_InfoProcess(ByVal str As String)
        Try
            '
            Dim recdata() As String = str.Split(",")
            temp(0) = photo_point(0)
            temp(1) = photo_point(1)
            'temp(4) = recdata(3)
            temp(2) = photo_point(4)
            temp(3) = photo_point(5)
            bzw = 1

            Dim proname As String = "cad_point"

            Dim Sql As String = "update " & proname & " set x=" & temp(0) & ",y=" & temp(1) & "  where PointName = 'photo1robot ' and Product='" & Chanpin & "'"
            HandleMysql(Sql)

            Sql = "update " & proname & " set x=" & temp(2) & ",y=" & temp(3) & " where PointName = 'photo2robot ' and Product='" & Chanpin & "'"
            HandleMysql(Sql)

            CadToRobot()    'cad_point计算至Robot_point
        Catch ex As Exception
            AppendInfoToTextBox("P_InfoProcess err:" & ex.Message.ToString)
            MsgBox("P_InfoProcess err:" & ex.Message.ToString)
        End Try

    End Sub

    Private Sub kill_InfoProcess(ByVal str As String)
        Try
            Dim ss() As String = str.Split(",")
            Dim sql1 As String = ""
            sql1 = " update " & " photo_point " & "set x=" & ss(1) & ",y=" & ss(2) & ",z=" & ss(3) & ",c=" & ss(4) & " where PointName=" & "'photo1robot' and Product='" & Chanpin & "'"

            HandleMysql(sql1)
            sql1 = " update " & " photo_point " & "set x=" & ss(5) & ",y=" & ss(6) & ",z=" & ss(7) & ",c=" & ss(8) & " where PointName=" & "'photo2robot' and Product='" & Chanpin & "'"

            HandleMysql(sql1)
            AutoAddPhotoPoint(1).X = ss(1)
            AutoAddPhotoPoint(1).Y = ss(2)
            AutoAddPhotoPoint(1).Z = ss(3)
            AutoAddPhotoPoint(1).C = ss(4)
            AutoAddPhotoPoint(2).X = ss(5)
            AutoAddPhotoPoint(2).Y = ss(6)
            AutoAddPhotoPoint(2).Z = ss(7)
            AutoAddPhotoPoint(2).C = ss(8)
            StepOK3 = True
        Catch ex As Exception
            AppendInfoToTextBox("kill_InfoProcess:" & ex.Message.ToString)
        End Try
    End Sub

    'Private Sub ConnectRobot()
    '    '开启通讯
    '    ' RoboCom.exe
    '    Dim a As Integer
    '    Dim RoboPath As String = DebugPath
    '    Try
    '        a = Shell(RoboPath & "\RT\RoboCom.exe", vbHide)
    '        If a = 0 Then
    '            MsgBox("机器人通讯程序打开失败！！")
    '        Else
    '            Button_RBConect.Text = "断开机器人"
    '            Button_RBConect.BackColor = Color.Lime
    '        End If

    '        '连接机器人
    '        Dim sStatus As Boolean
    '        Dim lCnt As Integer
    '        Dim sRobotInf As Object = New Char()
    '        Dim sRobotID As Object = New Char()
    '        Dim sName As Object = New Char()
    '        Dim sData As Object = New Char()
    '        'Information on the robot that the communication setting is done is obtained.

    '    Catch ex As Exception
    '        lRobotID = 0
    '        MsgBox("OpenRobotConnect:" & ex.Message.ToString & ex.StackTrace.ToString)
    '    End Try

    'End Sub

    Private Sub Button_RESET_Click(sender As Object, e As EventArgs)
        '复位报警407
        Dim sSendData As String = ""

    End Sub

    Private Sub TabControl1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles TabControl1.SelectedIndexChanged
        Try
            If TabControl1.SelectedTab.Name = "TabPage5" Then
            Else

            End If
            Pbutton_Change(TabControl1.SelectedIndex)
        Catch ex As Exception
            MsgBox("错误:" & ex.Message.ToString)
        End Try
    End Sub

    'Private Sub Button_Load_Click(sender As Object, e As EventArgs)
    '    Try
    '        '    Dim name As String = cmbUsername.SelectedItem.ToString
    '        '    Dim sql As String = "select UPwd,UPriority from userInfo where UName=" & "'" & name & "'"
    '        '    Dim cnStr As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source= Tool\user.accdb;Persist Security Info=False;Jet OLEDB:Database Password='1234'"
    '        '    ds1 = SearchDB(sql, cnStr)
    '        '    If ds1.Tables(0).Rows.Count > 0 Then
    '        '        If PasswordTextBox.Text = ds1.Tables(0).Rows(0)(0) And ds1.Tables(0).Rows(0)(1) = 1 Then
    '        '            gPriority = 1
    '        '        ElseIf PasswordTextBox.Text = ds1.Tables(0).Rows(0)(0) And ds1.Tables(0).Rows(0)(1) = 2 Then
    '        '            gPriority = 2
    '        '        ElseIf PasswordTextBox.Text = ds1.Tables(0).Rows(0)(0) And ds1.Tables(0).Rows(0)(1) = 3 Then
    '        '            gPriority = 3
    '        '        Else
    '        '            MsgBox("用户名或密码错误,请重新输入!")
    '        '            gPriority = 0
    '        '        End If
    '        '        If gPriority = 0 Then
    '        '            DataByPCS.OperatorID = ""
    '        '        Else
    '        '            DataByPCS.OperatorID = cmbUsername.Text
    '        '        End If

    '        '    End If
    '        '       gPriority = 1
    '        gEngineerPwd = GetSetting(My.Application.Info.Title, "Setting", "Engineer", "123")
    '        gAdminPwd = GetSetting(My.Application.Info.Title, "Setting", "Admin", "LNLON")

    '        Select Case TextBox_UserID.Text
    '            Case "Operator"

    '            Case "Engineer"
    '                If TextBox_PassWord.Text = gEngineerPwd Then
    '                    gPriority = 1
    '                    TextBox_OPID.Text = "Engineer"
    '                    TextBox_OPID.BackColor = Color.Lime
    '                Else
    '                    MsgBox("用户名或密码错误,请重新输入! ")
    '                    gPriority = 0
    '                End If
    '            Case "Admin"
    '                If TextBox_PassWord.Text = gAdminPwd Then
    '                    gPriority = 2
    '                    TextBox_OPID.Text = "Admin"
    '                    TextBox_OPID.BackColor = Color.Lime
    '                Else
    '                    MsgBox("用户名或密码错误,请重新输入! ")
    '                    gPriority = 0
    '                End If
    '            Case Else
    '                MsgBox("用户名或密码错误,请重新输入! ")
    '                Me.ShowDialog()
    '        End Select
    '        FrmAdmin.EnableMenu()
    '        TextBox_PassWord.Text = ""
    '        ' Me.Close()
    '    Catch ex As Exception
    '        MsgBox(ex.Message)
    '    End Try
    'End Sub

    'Private Sub Button_Exit_Click(sender As Object, e As EventArgs)
    '    Try
    '        gPriority = 0
    '        DataByPCS.OperatorID = ""
    '        TextBox_OPID.Text = "未登录"
    '        TextBox_OPID.BackColor = Color.WhiteSmoke
    '        FrmAdmin.EnableMenu()
    '        TextBox_PassWord.Text = ""
    '        TextBox_UserID.Text = ""
    '        Button_Load.Enabled = True
    '        Button_Exit.Enabled = False
    '        Button_Load.Text = "登录"
    '        Button_Load.BackColor = Color.WhiteSmoke
    '        Button_Load.UseVisualStyleBackColor = True
    '    Catch ex As Exception

    '    End Try
    'End Sub

    'Private Sub TextBox_ServConnect_TextChanged(sender As Object, e As EventArgs) Handles TextBox_ServConnect.TextChanged
    '    If TextBox_ServConnect.Text = "Connected" Then
    '        TextBox_ServConnect.BackColor = Color.Lime
    '    ElseIf TextBox_ServConnect.Text = "Disconnected" Then
    '        TextBox_ServConnect.BackColor = Color.Red
    '    Else
    '        TextBox_ServConnect.BackColor = Color.WhiteSmoke
    '    End If
    '    'TextBox_se.Text = TextBox_ServConnect.Text
    '    'TextBox_se.BackColor = TextBox_ServConnect.BackColor
    'End Sub

    'Private Sub Pbutton1_Click(sender As Object, e As EventArgs)
    '    Pbutton_Change(0)
    'End Sub

    Private Sub Pbutton2_Click(sender As Object, e As EventArgs) Handles Pbutton2.Click
        Pbutton_Change(0)
    End Sub

    Private Sub Pbutton3_Click(sender As Object, e As EventArgs) Handles Pbutton3.Click
        Pbutton_Change(1)
    End Sub

    Private Sub Pbutton4_Click(sender As Object, e As EventArgs) Handles Pbutton4.Click
        Pbutton_Change(2)
    End Sub

    Private Sub Pbutton5_Click(sender As Object, e As EventArgs) Handles Pbutton5.Click
        Pbutton_Change(3)
    End Sub

    Private Sub Pbutton6_Click(sender As Object, e As EventArgs) Handles Pbutton6.Click
        Pbutton_Change(4)
    End Sub

    Private Sub Pbutton_Change(ByVal PageNO As Integer)
        Try

            Dim colorB As Color = Color.Lime
            Dim colorW As Color = Color.Transparent
            TabControl1.SelectedIndex = PageNO

            Select Case PageNO
                'Case 0
                '    'Pbutton1.BackColor = colorB
                '    Pbutton2.BackColor = colorW
                '    Pbutton3.BackColor = colorW
                '    Pbutton4.BackColor = colorW
                '    Pbutton5.BackColor = colorW
                '    Pbutton6.BackColor = colorW

                Case 0
                    'Pbutton1.BackColor = colorW
                    Pbutton2.BackColor = colorB
                    Pbutton3.BackColor = colorW
                    Pbutton4.BackColor = colorW
                    Pbutton5.BackColor = colorW
                    Pbutton6.BackColor = colorW
                Case 1
                    'Pbutton1.BackColor = colorW
                    Pbutton2.BackColor = colorW
                    Pbutton3.BackColor = colorB
                    Pbutton4.BackColor = colorW
                    Pbutton5.BackColor = colorW
                    Pbutton6.BackColor = colorW
                Case 2
                    ' Pbutton1.BackColor = colorW
                    Pbutton2.BackColor = colorW
                    Pbutton3.BackColor = colorW
                    Pbutton4.BackColor = colorB
                    Pbutton5.BackColor = colorW
                    Pbutton6.BackColor = colorW
                Case 3
                    'Pbutton1.BackColor = colorW
                    Pbutton2.BackColor = colorW
                    Pbutton3.BackColor = colorW
                    Pbutton4.BackColor = colorW
                    Pbutton5.BackColor = colorB
                    Pbutton6.BackColor = colorW
                Case 4
                    'Pbutton1.BackColor = colorW
                    Pbutton2.BackColor = colorW
                    Pbutton3.BackColor = colorW
                    Pbutton4.BackColor = colorW
                    Pbutton5.BackColor = colorW
                    Pbutton6.BackColor = colorB
            End Select
        Catch ex As Exception

        End Try
    End Sub

    Private Sub Button3_Click_1(sender As Object, e As EventArgs) Handles Button3.Click
        TabControl1.SelectedIndex = 1
        Dim appwin As IntPtr
        Dim Process As Process
        Try
            Process = System.Diagnostics.Process.Start(exeName)
            Process.WaitForInputIdle()
            appwin = Process.MainWindowHandle
            System.Threading.Thread.Sleep(100)
        Catch ex As Exception
            MessageBox.Show(Me, ex.Message, "Error")
        End Try
        SetParent(appwin, Me.Panel1.Handle)
        MoveWindow(appwin, 0, 0, Me.Width, Me.Height, True)
        Timer1.Enabled = True

        SetCursorPos(600, 280)

        mouse_event(&H2, 0, 0, 0, 0) '鼠标左键按下

        mouse_event(&H4, 0, 0, 0, 0) '鼠标左键弹起
    End Sub

    '    Private Sub Button_RBConect_Click(sender As Object, e As EventArgs)
    '        Try
    '            If Button_RBConect.Text = "连接机器人" Then
    '                Dim a As Integer = Shell(DebugPath & "\RT\RoboCom.exe", vbHide)
    '                If a = 0 Then
    '                    MsgBox("机器人通讯程序打开失败！！")
    '                End If
    '                Button_RBConect.Text = "断开机器人"
    '                Button_RBConect.BackColor = Color.Lime

    '            Else
    '                '判断RT ToolBox2是否在运行
    '                For Each pro As Process In Process.GetProcesses()
    '                    If pro.ProcessName = "MELFA_RT" Then
    '                        GoTo d
    '                    End If
    '                Next
    '                Button_RBConect.Text = "连接机器人"
    '                Button_RBConect.BackColor = Color.WhiteSmoke
    '                Button_RBConect.UseVisualStyleBackColor = True

    '                '关闭连接
    '                Dim TargetKill() As Process = Process.GetProcessesByName("RoboCom") '从进程名获取进程
    '                If TargetKill.Length > 0 Then
    '                    For i = 0 To (TargetKill.Length - 1)
    '                        TargetKill(i).Kill()
    '                    Next
    '                End If
    'd:

    '            End If

    '        Catch ex As Exception

    '        End Try
    '    End Sub

    'Private Sub ComboBox_MainSpeed_SelectedIndexChanged(sender As Object, e As EventArgs)
    '    Try
    '        If ComboBox_MainSpeed.SelectedIndex > 0 Then
    '            Dim sSendData As String
    '            Dim lStatus As Integer
    '            Dim CommandCode As Integer = 404
    '            '
    '            sSendData = ComboBox_MainSpeed.Text

    '        End If
    '    Catch ex As Exception
    '        MsgBox("错误：" & ex.Message.ToString)
    '    End Try
    'End Sub

    Private Sub Count_Clear_Click_1(sender As Object, e As EventArgs) Handles Count_Clear.Click
        Todaycount.NGCount = 0
        Todaycount.PassCount = 0
        Todaycount.SCount = 0
        Todaycount.Screwcount = 0
        Todaycount.ScrewFailed1 = 0
        Todaycount.ScrewFailed2 = 0
        Todaycount.ScrewFailed3 = 0
        Todaycount.ScrewFailed4 = 0
        Todaycount.ScrewFailed5 = 0
        Todaycount.ScrewFailed6 = 0
        Todaycount.ScrewFailed7 = 0
        Todaycount.ScrewFailed8 = 0
        Todaycount.ScrewFailed9 = 0
        Todaycount.ScrewFailed10 = 0
        Todaycount.ScrewFailed11 = 0
        Todaycount.ScrewFailed12 = 0
        Todaycount.ScrewFailed13 = 0
        Todaycount.ScrewFailed14 = 0
        Todaycount1.ScrewFailed15 = 0
        Todaycount1.ScrewFailed16 = 0
        Todaycount1.ScrewFailed17 = 0
        Todaycount1.ScrewFailed18 = 0
        Todaycount1.ScrewFailed19 = 0
        Todaycount1.ScrewFailed20 = 0
        Todaycount1.ScrewFailed21 = 0
        Todaycount1.ScrewFailed22 = 0
        Todaycount1.ScrewFailed23 = 0
        Todaycount1.ScrewFailed24 = 0
        Todaycount1.ScrewFailed25 = 0
        Todaycount1.ScrewFailed26 = 0
        Todaycount1.ScrewFailed27 = 0
        Todaycount1.ScrewFailed28 = 0
        Todaycount1.ScrewFailed29 = 0
        Todaycount1.ScrewFailed30 = 0
        Todaycount.SFTime = 0
        Todaycount.IDELTime = 0
        Todaycount.ShutDownTime = 0
        TextBox6.Text = Todaycount.Screwcount.ToString
        TextBox1.Text = Todaycount.PassCount.ToString
        TextBox2.Text = Todaycount.NGCount.ToString
        TextBox3.Text = Todaycount.SCount.ToString
        TextBox7.Text = "100.00%"
        mainInfo.Yield = TextBox7.Text
        ScrewFailed1.Text = Todaycount.ScrewFailed1.ToString
        ScrewFailed2.Text = Todaycount.ScrewFailed2.ToString
        ScrewFailed3.Text = Todaycount.ScrewFailed3.ToString
        ScrewFailed4.Text = Todaycount.ScrewFailed4.ToString
        ScrewFailed5.Text = Todaycount.ScrewFailed5.ToString
        ScrewFailed6.Text = Todaycount.ScrewFailed6.ToString
        ScrewFailed7.Text = Todaycount.ScrewFailed7.ToString
        ScrewFailed8.Text = Todaycount.ScrewFailed8.ToString
        ScrewFailed9.Text = Todaycount.ScrewFailed9.ToString
        ScrewFailed10.Text = Todaycount.ScrewFailed10.ToString
        ScrewFailed11.Text = Todaycount.ScrewFailed11.ToString
        ScrewFailed12.Text = Todaycount.ScrewFailed12.ToString
        ScrewFailed13.Text = Todaycount.ScrewFailed13.ToString
        ScrewFailed14.Text = Todaycount.ScrewFailed14.ToString
        ScrewFailed15.Text = Todaycount1.ScrewFailed15.ToString
        ScrewFailed16.Text = Todaycount1.ScrewFailed16.ToString
        ScrewFailed17.Text = Todaycount1.ScrewFailed17.ToString
        ScrewFailed18.Text = Todaycount1.ScrewFailed18.ToString
        ScrewFailed19.Text = Todaycount1.ScrewFailed19.ToString
        ScrewFailed20.Text = Todaycount1.ScrewFailed20.ToString
        ScrewFailed21.Text = Todaycount1.ScrewFailed21.ToString
        ScrewFailed22.Text = Todaycount1.ScrewFailed22.ToString
        ScrewFailed23.Text = Todaycount1.ScrewFailed23.ToString
        ScrewFailed24.Text = Todaycount1.ScrewFailed24.ToString
        ScrewFailed25.Text = Todaycount1.ScrewFailed25.ToString
        ScrewFailed26.Text = Todaycount1.ScrewFailed26.ToString
        ScrewFailed27.Text = Todaycount1.ScrewFailed27.ToString
        ScrewFailed28.Text = Todaycount1.ScrewFailed28.ToString
        ScrewFailed29.Text = Todaycount1.ScrewFailed29.ToString
        ScrewFailed30.Text = Todaycount1.ScrewFailed30.ToString
        SFTime.Text = Todaycount.SFTime
        IDELTime.Text = Todaycount.IDELTime
        SDTime.Text = Todaycount.ShutDownTime
        '新增异常台数、cycle time
        Todaycount2.PCSFailed = 0
        Todaycount2.CycleTime = 0
        Todaycount2.SuctionCount = 0
        Todaycount2.Height_float = 0
        TextBox_CT.Text = Todaycount2.CycleTime.ToString
        TextBox_Yield.Text = "100.00%"
        TextBox_PCSFailed.Text = Todaycount2.PCSFailed.ToString
        TextBox5.Text = 0
        TextBox14.Text = 0
        '异常管理
        'ScrewFailed_1.Text = Todaycount.ScrewFailed1.ToString
        'ScrewFailed_2.Text = Todaycount.ScrewFailed2.ToString
        'ScrewFailed_3.Text = Todaycount.ScrewFailed3.ToString
        'ScrewFailed_4.Text = Todaycount.ScrewFailed4.ToString
        'ScrewFailed_5.Text = Todaycount.ScrewFailed5.ToString
        'ScrewFailed_6.Text = Todaycount.ScrewFailed6.ToString
        'ScrewFailed_7.Text = Todaycount.ScrewFailed7.ToString
        'ScrewFailed_8.Text = Todaycount.ScrewFailed8.ToString
        'ScrewFailed_9.Text = Todaycount.ScrewFailed9.ToString
        'ScrewFailed_10.Text = Todaycount.ScrewFailed10.ToString
        'ScrewFailed_11.Text = Todaycount.ScrewFailed11.ToString
        'ScrewFailed_12.Text = Todaycount.ScrewFailed12.ToString
        'ScrewFailed_13.Text = Todaycount.ScrewFailed13.ToString
        'ScrewFailed_14.Text = Todaycount.ScrewFailed14.ToString
        'ScrewFailed_15.Text = Todaycount1.ScrewFailed15.ToString
        'ScrewFailed_16.Text = Todaycount1.ScrewFailed16.ToString
        'ScrewFailed_17.Text = Todaycount1.ScrewFailed17.ToString
        'ScrewFailed_18.Text = Todaycount1.ScrewFailed18.ToString
        'ScrewFailed_19.Text = Todaycount1.ScrewFailed19.ToString
        'ScrewFailed_20.Text = Todaycount1.ScrewFailed20.ToString
        'ScrewFailed_21.Text = Todaycount1.ScrewFailed21.ToString
        'ScrewFailed_22.Text = Todaycount1.ScrewFailed22.ToString
        'ScrewFailed_23.Text = Todaycount1.ScrewFailed23.ToString
        'ScrewFailed_24.Text = Todaycount1.ScrewFailed24.ToString
        'ScrewFailed_25.Text = Todaycount1.ScrewFailed25.ToString
        'ScrewFailed_26.Text = Todaycount1.ScrewFailed26.ToString
        'ScrewFailed_27.Text = Todaycount1.ScrewFailed27.ToString
        'ScrewFailed_28.Text = Todaycount1.ScrewFailed28.ToString
        'ScrewFailed_29.Text = Todaycount1.ScrewFailed29.ToString
        'ScrewFailed_30.Text = Todaycount1.ScrewFailed30.ToString
        Todaycount3.SkipFailed1 = 0
        Todaycount3.SkipFailed2 = 0
        Todaycount3.SkipFailed3 = 0
        Todaycount3.SkipFailed4 = 0
        Todaycount3.SkipFailed5 = 0
        Todaycount3.SkipFailed6 = 0
        Todaycount3.SkipFailed7 = 0
        Todaycount3.SkipFailed8 = 0
        Todaycount3.SkipFailed9 = 0
        Todaycount3.SkipFailed10 = 0
        Todaycount3.SkipFailed11 = 0
        Todaycount3.SkipFailed12 = 0
        Todaycount3.SkipFailed13 = 0
        Todaycount3.SkipFailed14 = 0
        Todaycount4.SkipFailed15 = 0
        Todaycount4.SkipFailed16 = 0
        Todaycount4.SkipFailed17 = 0
        Todaycount4.SkipFailed18 = 0
        Todaycount4.SkipFailed19 = 0
        Todaycount4.SkipFailed20 = 0
        Todaycount4.SkipFailed21 = 0
        Todaycount4.SkipFailed22 = 0
        Todaycount4.SkipFailed23 = 0
        Todaycount4.SkipFailed24 = 0
        Todaycount4.SkipFailed25 = 0
        Todaycount4.SkipFailed26 = 0
        Todaycount4.SkipFailed27 = 0
        Todaycount4.SkipFailed28 = 0
        Todaycount4.SkipFailed29 = 0
        Todaycount4.SkipFailed30 = 0
        SkipFailed1.Text = Todaycount3.SkipFailed1.ToString
        SkipFailed2.Text = Todaycount3.SkipFailed2.ToString
        SkipFailed3.Text = Todaycount3.SkipFailed3.ToString
        SkipFailed4.Text = Todaycount3.SkipFailed4.ToString
        SkipFailed5.Text = Todaycount3.SkipFailed5.ToString
        SkipFailed6.Text = Todaycount3.SkipFailed6.ToString
        SkipFailed7.Text = Todaycount3.SkipFailed7.ToString
        SkipFailed8.Text = Todaycount3.SkipFailed8.ToString
        SkipFailed9.Text = Todaycount3.SkipFailed9.ToString
        SkipFailed10.Text = Todaycount3.SkipFailed10.ToString
        SkipFailed11.Text = Todaycount3.SkipFailed11.ToString
        SkipFailed12.Text = Todaycount3.SkipFailed12.ToString
        SkipFailed13.Text = Todaycount3.SkipFailed13.ToString
        SkipFailed14.Text = Todaycount3.SkipFailed14.ToString
        SkipFailed15.Text = Todaycount4.SkipFailed15.ToString
        SkipFailed16.Text = Todaycount4.SkipFailed16.ToString
        SkipFailed17.Text = Todaycount4.SkipFailed17.ToString
        SkipFailed18.Text = Todaycount4.SkipFailed18.ToString
        SkipFailed19.Text = Todaycount4.SkipFailed19.ToString
        SkipFailed20.Text = Todaycount4.SkipFailed20.ToString
        SkipFailed21.Text = Todaycount4.SkipFailed21.ToString
        SkipFailed22.Text = Todaycount4.SkipFailed22.ToString
        SkipFailed23.Text = Todaycount4.SkipFailed23.ToString
        SkipFailed24.Text = Todaycount4.SkipFailed24.ToString
        SkipFailed25.Text = Todaycount4.SkipFailed25.ToString
        SkipFailed26.Text = Todaycount4.SkipFailed26.ToString
        SkipFailed27.Text = Todaycount4.SkipFailed27.ToString
        SkipFailed28.Text = Todaycount4.SkipFailed28.ToString
        SkipFailed29.Text = Todaycount4.SkipFailed29.ToString
        SkipFailed30.Text = Todaycount4.SkipFailed30.ToString
        ''''''''''
        Dim filepath = DebugPath & "\Tool\"
        If Exists(filepath & "\count.txt") Then
            '      Kill(filepath & TCmbPro.Text & "\count.txt")
            FileOpen(file_num_count, filepath & "\count.txt", OpenMode.Random)
            FilePut(file_num_count, Todaycount)
            FileClose(file_num_count)
        End If
        If Exists(filepath & "\count1.txt") Then
            '      Kill(filepath & TCmbPro.Text & "\count.txt")
            FileOpen(file_num_count, filepath & "\count1.txt", OpenMode.Random)
            FilePut(file_num_count, Todaycount1)
            FileClose(file_num_count)
        End If
        If Exists(filepath & "\count2.txt") Then
            'Kill(filepath & TCmbPro.Text & "\count.txt")
            FileOpen(file_num_count, filepath & "\count2.txt", OpenMode.Random)
            FilePut(file_num_count, Todaycount2)
            FileClose(file_num_count)
        End If
        If Exists(filepath & "\count3.txt") Then
            'Kill(filepath & TCmbPro.Text & "\count.txt")
            FileOpen(file_num_count, filepath & "\count3.txt", OpenMode.Random)
            FilePut(file_num_count, Todaycount3)
            FileClose(file_num_count)
        End If
        If Exists(filepath & "\count4.txt") Then
            'Kill(filepath & TCmbPro.Text & "\count.txt")
            FileOpen(file_num_count, filepath & "\count4.txt", OpenMode.Random)
            FilePut(file_num_count, Todaycount4)
            FileClose(file_num_count)
        End If
    End Sub

    Private Sub 扫码管理ToolStripMenuItem_Click(sender As System.Object, e As System.EventArgs) Handles 扫码管理ToolStripMenuItem.Click
        扫码模板管理.ShowDialog()
    End Sub

    Private Sub 螺丝扫码管理ToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles 螺丝扫码管理ToolStripMenuItem.Click
        螺丝扫码管理.ShowDialog()
    End Sub

    Private Sub 设备信息设置ToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles 设备信息设置ToolStripMenuItem.Click
        FrmMachine.ShowDialog()
    End Sub

    ''' <summary>
    ''' 打开数据上传程序
    ''' </summary>
    ''' <remarks></remarks>
    Private Sub OpenUploadProcess()
        Try
            If newset(7) Then
                'Dim a As Integer
                'a = Shell(UploadPath & "\Upload.exe", vbNormalFocus)
                'If a = 0 Then
                '    MsgBox("数据上传程序打开失败！！")
                'End If
            End If
        Catch ex As Exception
            MsgBox("OpenUploadProcess:" & ex.Message.ToString & ex.StackTrace.ToString)
        End Try

    End Sub

    ''' <summary>
    ''' 关闭数据上传程序
    ''' </summary>
    ''' <remarks></remarks>
    Public Sub CloseUploadProcess()
        Try
            Dim winHwnd As IntPtr = FindWindow(vbNullString, "数据上传")
            Dim RetVal As IntPtr
            If winHwnd <> 0 Then
                RetVal = PostMessage(winHwnd, WM_CLOSE, 0&, 0&)
            End If
        Catch ex As Exception
            MsgBox("CloseUploadProcess:" & ex.Message.ToString & ex.StackTrace.ToString)
        End Try

    End Sub

    Private Sub CheckUploadEXE_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CheckUploadEXE.Tick
        Try
            Dim winHwnd As IntPtr = FindWindow(vbNullString, "数据上传")
            If newset(7) = False Then
                TextBox8_UpLoadStatus.BackColor = Color.Red
                TextBox8_UpLoadStatus.Text = "关闭"
            Else
                TextBox8_UpLoadStatus.BackColor = Color.Lime
                TextBox8_UpLoadStatus.Text = "开启"
            End If
        Catch ex As Exception
            AppendInfoToTextBox("CheckUploadEXE_Tick:" & ex.Message.ToString)
        End Try
    End Sub

    Private Sub ClearAllQueue_Click(sender As Object, e As EventArgs)
        If MessageBox.Show("确定要清空队列所有元素吗？", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question) = Windows.Forms.DialogResult.Yes Then
            Try
                If Tcmb_Queue.Count > 0 Then
                    Tcmb_Queue.Clear()
                End If
                If SN_Queue.Count > 0 Then
                    SN_Queue.Clear()
                    'SendMessageToUpload("ClearQueue", "0")
                End If
                'ShowQueueList()
            Catch ex As Exception
                MsgBox("ClearAllQueue_Click:" & ex.Message.ToString)
            End Try

        End If
    End Sub

    Private Sub ClearFirstQueue_Click(sender As Object, e As EventArgs)
        If MessageBox.Show("确定要清除队首" & SN_Queue(0).sn & "," & Tcmb_Queue(0) & "吗？", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question) = Windows.Forms.DialogResult.Yes Then
            Try
                '急停

                If Tcmb_Queue.Count > 0 Then
                    Tcmb_Queue.Dequeue()
                End If
                If SN_Queue.Count > 0 Then
                    SN_Queue.Dequeue()
                    'SendMessageToUpload("ClearQueue", "1")
                End If
                'ShowQueueList()
            Catch ex As Exception
                MsgBox("ClearFirstQueue_Click:" & ex.Message.ToString)
            End Try

        End If
    End Sub

    ' ''' <summary>
    ' ''' 显示模版队列信息
    ' ''' </summary>
    ' ''' <remarks></remarks>
    'Private Sub ShowQueueList()
    '    Try
    '        TcmbQueueList.Text = ""
    '        If Tcmb_Queue.Count > 0 Then
    '            For i As Integer = 0 To Tcmb_Queue.Count - 1
    '                TcmbQueueList.AppendText(Tcmb_Queue(i) & vbCrLf)
    '                AppendInfoToTextBox("模版名" & i + 1 & ":" & Tcmb_Queue(i) & vbCrLf)
    '            Next
    '        End If
    '        SNQueueList.Text = ""
    '        If SN_Queue.Count > 0 Then
    '            For i As Integer = 0 To SN_Queue.Count - 1
    '                SNQueueList.AppendText(SN_Queue(i) & vbCrLf)
    '            Next
    '        End If
    '    Catch ex As Exception
    '        MsgBox("ShowQueueList:" & ex.Message.ToString)
    '    End Try

    'End Sub

    Private Sub UploadStatus_Tick(sender As Object, e As EventArgs) Handles UploadStatus.Tick

        'uploadstate()

    End Sub

    Private Sub UploadMainInfo_Tick(sender As Object, e As EventArgs) Handles UploadMainInfo.Tick
        'upload_MainInfo()
        'Dim WM_SETFOCUS As IntPtr = &H7
        'Dim WM_SETTEXT As IntPtr = &HC
        'Dim s As String = machineInfoStatus.Device_type & "," & machineInfoStatus.Manufacturer & "," & machineInfoStatus.Device_Code & "," & machineInfoStatus.Device_id & "," & machineInfoStatus.Line & "," & machineInfoStatus.IP & "," & machineInfoStatus.Status
        'Dim lngCalculator As IntPtr = FindWindow(vbNullString, "数据上传")
        'Dim Line As IntPtr = FindWindowEx(lngCalculator, 0, vbNullString, "MachineStatus")
        'Dim i As Integer = SendMessage(Line, WM_SETTEXT, 0, s)
        'If i = 0 Then
        '    AppendInfoToTextBox("状态发送失败,数据上传程序已断开")
        'End If
    End Sub

    ''' <summary>
    ''' 获取服务器的时间
    ''' </summary>
    ''' <returns></returns>
    ''' <remarks></remarks>
    'Public Function getServerTime() As String
    '    Try
    '        If newset(7) Then
    '            Dim sql As String = "select DATE_FORMAT(now(3),'%Y%m%d%H%i%s%f')"
    '            Dim ds As DataSet = New DataSet
    '            ds = SearchMysql(sql)
    '            If ds.Tables(0).Rows.Count > 0 Then
    '                Return (ds.Tables(0).Rows(0)(0).ToString).Substring(0, 17)
    '            Else
    '                Return ""
    '            End If
    '        Else
    '            Return ""
    '        End If

    '    Catch ex As Exception
    '        MsgBox("getServerTime:" & ex.Message.ToString)
    '        Return ""
    '    End Try
    'End Function
    Public Sub uploadstate()
        'Dim WM_SETFOCUS As IntPtr = &H7
        'Dim WM_SETTEXT As IntPtr = &HC
        Dim s As String = machineInfoStatus.Device_type & "," & machineInfoStatus.Manufacturer & "," & machineInfoStatus.Device_Code & "," & machineInfoStatus.Device_id & "," & machineInfoStatus.Line & "," & machineInfoStatus.IP & "," & machineInfoStatus.Status & "," & machineInfoStatus.ErrorCode
        SendMessageToUpload("MachineStatus", s)
        'Dim lngCalculator As IntPtr = FindWindow(vbNullString, "数据上传")
        'Dim Line As IntPtr = FindWindowEx(lngCalculator, 0, vbNullString, "MachineStatus")
        'Dim i As Integer = SendMessage(Line, WM_SETTEXT, 0, s)
        'If i = 0 Then
        '    'AppendInfoToTextBox("状态发送失败,数据上传程序已断开")
        '    OpenUploadProcess()
        'End If
    End Sub

    Public Sub upload_MainInfo()
        'Dim WM_SETFOCUS As IntPtr = &H7
        'Dim WM_SETTEXT As IntPtr = &HC
        Dim s As String = mainInfo.Device_id & "," & mainInfo.Line & "," & Todaycount.PassCount & "," & Todaycount.Screwcount & "," & Todaycount.SCount & "," & Todaycount.NGCount & "," & mainInfo.Yield & "," & mainInfo.RunTime & "," & Format(Todaycount.SFTime, "0.0") & "," & Format(Todaycount.IDELTime, "0.0") & "," & Format(Todaycount.ShutDownTime, "0.0")
        'AppendInfoToTextBox(s)
        SendMessageToUpload("MainInfo", s)
        'Dim lngCalculator As IntPtr = FindWindow(vbNullString, "数据上传")
        'Dim Line As IntPtr = FindWindowEx(lngCalculator, 0, vbNullString, "MainInfo")
        'Dim i As Integer = SendMessage(Line, WM_SETTEXT, 0, s)
        'If i = 0 Then
        '    'AppendInfoToTextBox("生产数据发送失败,数据上传程序已断开")
        '    OpenUploadProcess()
        'End If
    End Sub

    Public Sub upload_SNInfo()
        Try
            'Dim WM_SETFOCUS As IntPtr = &H7
            'Dim WM_SETTEXT As IntPtr = &HC

            'Dim Info As String = ";"
            If SN_Queue.Count > 0 Then
                Dim Info As String = GetInfoBySN(SN_Queue(0))
                'If SN_Queue(0) = "123" Then
                '    Info = "LCMSize-14.5;SCDY0101F07X"
                'ElseIf SN_Queue(0) = "321" Then
                '    Info = "LCMSize-15.5;SCDY0101F07Y"
                'End If
                SNInfo.SN = SN_Queue(0).sn
                Dim recdata() As String = Info.Split(";")

                SNInfo.Family = recdata(1)
            Else
                SNInfo.SN = SNInfo.Device_id & SNInfo.SF_Cdt_Begin
                'SNInfo.Family = FrmMachine.Family.Text
            End If

            Dim s As String = SNInfo.Device_id & "," & SNInfo.Line & "," & SNInfo.Family & "," & SNInfo.SN & "," & SNInfo.SF_Cdt_Begin & "," & SNInfo.SF_Cdt_End & "," & SNInfo.Screw_Qty & "," & SF_Fail_Qty_Single & "," & SB_Fail_Qty_Single & "," & IIf(SF_Fail_Qty_Single = 0 And SB_Fail_Qty_Single = 0, 0, 1)
            'AppendInfoToTextBox(s)
            SendMessageToUpload("SNInfo", s)
            'Dim lngCalculator As IntPtr = FindWindow(vbNullString, "数据上传")
            'Dim Line As IntPtr = FindWindowEx(lngCalculator, 0, vbNullString, "SNInfo")
            'Dim i As Integer = SendMessage(Line, WM_SETTEXT, 0, s)
            'If i = 0 Then
            '    'AppendInfoToTextBox("SN信息发送失败,数据上传程序已断开")
            '    OpenUploadProcess()
            'End If
        Catch ex As Exception
            AppendInfoToTextBox("upload_SNInfo:" & ex.Message.ToString)
        End Try
    End Sub

    Public Sub upload_SNDetail()
        Try
            'Dim WM_SETFOCUS As IntPtr = &H7
            'Dim WM_SETTEXT As IntPtr = &HC
            If SN_Queue.Count > 0 Then
                SNDetail.SN = SN_Queue(0).sn
            Else
                SNDetail.SN = SNInfo.Device_id & SNInfo.SF_Cdt_Begin
            End If
            Dim info As String = SNDetail.SN & "," & SNDetail.NumOfScrew & "," & SNDetail.Screw_A1 & "," & SNDetail.TorqueValue & "," & SNDetail.Status & "," & SNDetail.ErrType & "," & SNDetail.SF_Cdt_Begin & "," & SNDetail.SF_Cdt_End

            'AppendInfoToTextBox(info)
            SendMessageToUpload("SNDetail", info)
            'Dim lngCalculator As IntPtr = FindWindow(vbNullString, "数据上传")
            'Dim Line As IntPtr = FindWindowEx(lngCalculator, 0, vbNullString, "SNDetail")
            'Dim i As Integer = SendMessage(Line, WM_SETTEXT, 0, info)
            'If i = 0 Then
            '    'AppendInfoToTextBox("锁附详细信息发送失败,数据上传程序已断开")
            '    OpenUploadProcess()
            'End If
        Catch ex As Exception
            AppendInfoToTextBox("upload_SNDetail:" & ex.Message.ToString)
        End Try
    End Sub

    Public Sub SendMessageToUpload(ByVal TBoxText As String, ByVal content As String)
        Try
            Dim WM_SETFOCUS As IntPtr = &H7
            Dim WM_SETTEXT As IntPtr = &HC
            Dim lngCalculator As IntPtr = FindWindow(vbNullString, "数据上传")
            Dim Line As IntPtr = FindWindowEx(lngCalculator, 0, vbNullString, TBoxText)
            Dim i As Integer = SendMessage(Line, WM_SETTEXT, 0, content)
            If i = 0 Then
                'AppendInfoToTextBox("锁附详细信息发送失败,数据上传程序已断开")
                'OpenUploadProcess()
            End If
        Catch ex As Exception
            AppendInfoToTextBox("SendMessageToUpload:" & ex.Message.ToString)
        End Try
    End Sub

    Private Function HXtoB(ByVal s As String)
        Try
            Dim value As String = "0000"
            If s = "0" Then
                value = "0000"
            End If
            If s = "1" Then
                value = "0001"
            End If
            If s = "2" Then
                value = "0010"
            End If
            If s = "3" Then
                value = "0011"
            End If
            If s = "4" Then
                value = "0100"
            End If
            If s = "5" Then
                value = "0101"
            End If
            If s = "6" Then
                value = "0110"
            End If
            If s = "7" Then
                value = "0111"
            End If
            If s = "8" Then
                value = "1000"
            End If
            If s = "9" Then
                value = "1001"
            End If
            If s = "A" Or s = "a" Then
                value = "1010"
            End If
            If s = "B" Or s = "b" Then
                value = "1011"
            End If
            If s = "C" Or s = "c" Then
                value = "1100"
            End If
            If s = "D" Or s = "d" Then
                value = "1101"
            End If
            If s = "E" Or s = "e" Then
                value = "1110"
            End If
            If s = "F" Or s = "f" Then
                value = "1111"
            End If
            Return value
        Catch ex As Exception
            AppendInfoToTextBox("HXtoB:" & ex.Message.ToString)
        End Try
    End Function

    '    Private Sub AxMelfaRxM1_MsgRecvEvent(sender As Object, e As EventArgs) Handles AxMelfaRxM1.MsgRecvEvent
    '        Dim lState As Integer
    '        Dim lReqID As Integer
    '        Dim sRecvData As Object = New Char()
    '        Dim lStatus As Integer
    '        Dim lError As Integer
    '        Dim lCnt As Integer
    '        Dim sOneData As Object = New Char()
    '        Dim sData As String = ""
    '        Dim lRobotID As Integer
    '        Try
    '            lState = AxMelfaRxM1.GetRecvDataM(lRobotID, lReqID, sRecvData, lStatus, lError)

    '            If lStatus <> 1 Then
    '                MsgBox(sRecvData)

    '            Else
    '                lCnt = AxMelfaRxM1.GetDataCnt(sRecvData)
    '                '214
    '                If lReqID = 214 Then
    '                    Dim ss() As String
    '                    ' ReDim ss(sRecvData.Length)
    '                    ss = sRecvData.Split(Chr(10))
    '                    '  2479
    '                    Receive_IOValue(0) = ss(2)
    '                    Receive_IOValue(1) = ss(4)
    '                    Receive_IOValue(2) = ss(7)
    '                    Receive_IOValue(3) = ss(9)
    '                    GoTo d

    '                End If

    '            End If

    'd:
    '        Catch ex As Exception
    '            AppendInfoToTextBox("AxMelfaRxM1_MsgRecvEvent:" & ex.Message.ToString)
    '        End Try
    '    End Sub

    Private Sub Timer3_Tick(sender As Object, e As EventArgs) Handles Timer3.Tick
        mainInfo.RunTime += 1
        bootTime.Text = mainInfo.RunTime
    End Sub

    Private Function UseAxM1(ByVal s As String)
        Try
            If (TxtResult1.InvokeRequired) Then
                Dim cb As UseAxM = New UseAxM(AddressOf UseAxM1)
                Invoke(cb)
            Else

            End If
        Catch ex As Exception
            AppendInfoToTextBox("UseAxM1:" & ex.Message.ToString)
        End Try
    End Function

    Private Sub GetPointWay()
        Dim i As Integer = 0
        Try
            Dim DBpath As String = DebugPath & "\Tool\" & TCmbPro.Text & "\PointWay.accdb"

            If File.Exists(DBpath) = False Then '没有文件,直接跳过
                GoTo d
            End If
            Dim sql1 As String = "select * from PointPara where Product='" & TCmbPro.Text & "'" '产品表单模板名字'产品表单模板名字"
            Dim cnStr As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & DBpath & ";Persist Security Info=False;Jet OLEDB:Database Password='1234'"

            Dim pointData As DataSet = New DataSet
            pointData = SearchMysql(sql1)
            For i = 1 To 30
                PointWay(i) = pointData.Tables(0).Rows(i - 1)("Way")
                PointHigh(i) = pointData.Tables(0).Rows(i - 1)("High")
                Point_X轴C(i) = pointData.Tables(0).Rows(i - 1)("X轴角度")
                Point_Y轴C(i) = pointData.Tables(0).Rows(i - 1)("Y轴角度")
            Next
d:
        Catch ex As Exception
            MsgBox("SavePointPara err:" & ex.Message.ToString)
        End Try
    End Sub

    ''' <summary>
    ''' 发送点位斜锁方式,高度,X轴角度,Y轴角度 参数
    ''' </summary>
    ''' <param name="MySocket"></param>
    ''' <param name="StrReceData"></param>
    ''' <remarks></remarks>
    Private Sub SendXieShuJu(ByRef MySocket As Socket, ByVal StrReceData As String)
        Dim Strdata As String = ""
        Dim byteSend As Byte()
        Dim i, j As Integer
        j = Val(CurScrewPara.PointCount)
        Try
            For i = 1 To j
                Strdata = Format(PointWay(i), "0.00") + "," + Format(PointHigh(i), "0.00") + "," + Format(Point_X轴C(i), "0.00") + "," + Format(Point_Y轴C(i), "0.00") + ","
                byteSend = Encoding.ASCII.GetBytes(Strdata + vbCrLf)
                AppendInfoToTextBox("send3:" + Strdata + vbCrLf)
                MySocket.Send(byteSend)
                waitstandby(200)
            Next
        Catch ex As Exception
            AppendInfoToTextBox("Err in SendXieShuJu:" & ex.Message.ToString & ex.StackTrace.ToString)
        End Try
    End Sub

#Region "西门子plc通讯"""

    Dim PLC As New WinTcpS7_Smart.PlcClient
    Dim EntLink As Boolean
    Dim Handle1 As Int32

    ''' 连接西门子PLC
    ''' <summary>
    '''
    '''
    Protected Sub SIEMENS_PLC_Communications_link()
        Dim K As Integer = 0
        Try
            Dim re As Short
            Dim restr As String = ""
            For K = 0 To 3
                re = PLC.EntLink("192.168.1.101", "8015", "192.168.1.55", "102", 0, 2, "LFL2017101218294%13274927708@S7200/SMART-TCP-V32", Handle1)
                If re = 0 Then
                    EntLink = True
                    K = 10
                    AppendInfoToTextBox("西门子PLC联接成功！")
                Else
                    EntLink = False
                    AppendInfoToTextBox("第" & K + 1 & "西门子PLC联接失败！")
                    wait(10000)
                End If
            Next
            If EntLink = False Then
                MsgBox("西门子PLC联接失败!请检查网络")
            End If
        Catch ex As Exception
            AppendInfoToTextBox(ex.Message.ToString)
            MsgBox(ex.Message.ToString & vbCrLf & ex.StackTrace.ToString)
        End Try
    End Sub

    '''    从西门子plc读取数据
    '''    ReadMry     读取存储区类型  I Q M V
    '''    ReadAdd     读取数据偏移量
    '''    ReadCnt     读取个数
    '''    ReadType    读取类型   "W_INT16"  "W_UINT16"  "D_DINT32"  "D_HEX32"  "D_REAL32"  "W_BIN16"  "B_CHAR8"   "B_BYTE8"
    '''    读取实例  Dim kkk() As String= SIEMENS_PLC_butRead（"V","1000","10","W_INT16"）
    Protected Function SIEMENS_PLC_butRead(ByVal ReadMry As String, ByVal ReadAdd As String, ByVal ReadCnt As String, ByVal ReadType As String) As String()
        Dim ScanRet As Short
        Dim SHUJU(ReadCnt) As String
        Dim i As Short
        Dim RD() As Object
        Dim J As Integer
        Dim K As Integer
        ReDim RD(Val(ReadCnt - 1))
        If Not EntLink Then
            MsgBox("还未与PLC建立联接！")
            Exit Function
        End If

        If ReadType = "W_INT16" Then
            K = 0
        ElseIf ReadType = "W_UINT16" Then
            K = 1
        ElseIf ReadType = "D_DINT32" Then
            K = 2
        ElseIf ReadType = "D_HEX32" Then
            K = 3
        ElseIf ReadType = "D_REAL32" Then
            K = 4
        ElseIf ReadType = "W_BIN16" Then
            K = 5
        ElseIf ReadType = "B_CHAR8" Then
            K = 6
        ElseIf ReadType = "B_BYTE8" Then
            K = 7
        End If
        Dim var1 As Integer = K + 1
        Dim typ As WinTcpS7_Smart.PlcClient.DataType = var1

        If ReadMry = "I" Then
            J = 1
        ElseIf ReadMry = "Q" Then
            J = 2
        ElseIf ReadMry = "M" Then
            J = 3
        ElseIf ReadMry = "V" Then
            J = 4
        End If
        Select Case J
            Case 1 : ScanRet = PLC.CmdRead(Handle1, WinTcpS7_Smart.PlcClient.PlcMemory.DI, typ, Val(ReadAdd), Val(ReadCnt), RD)
            Case 2 : ScanRet = PLC.CmdRead(Handle1, WinTcpS7_Smart.PlcClient.PlcMemory.DQ, typ, Val(ReadAdd), Val(ReadCnt), RD)
            Case 3 : ScanRet = PLC.CmdRead(Handle1, WinTcpS7_Smart.PlcClient.PlcMemory.MR, typ, Val(ReadAdd), Val(ReadCnt), RD)
            Case 4 : ScanRet = PLC.CmdRead(Handle1, WinTcpS7_Smart.PlcClient.PlcMemory.DR, typ, Val(ReadAdd), Val(ReadCnt), RD)
        End Select
        'txtReRead.Text = ScanRet.ToString
        'lstRead.Items.Clear()
        For i = 0 To UBound(RD) Step 1
            If Not IsNothing(RD(i)) Then
                SHUJU(i) = RD(i)
            Else
                SHUJU(i) = "0"
            End If
        Next i
        Return SHUJU
    End Function

    '''    写入到西门子PLC中
    '''    WriteMry   写入存储区类型  I Q M V
    '''    WriteAdd   写入数据偏移量
    '''    WriteCnt   写入个数
    '''    WriteType  写入类型   "W_INT16"  "W_UINT16"  "D_DINT32"  "D_HEX32"  "D_REAL32"  "W_BIN16"  "B_CHAR8"   "B_BYTE8"
    '''    读取实例  注意：数组数必须大于写入个数
    '''     Dim shuzhuWWW() As String = {""}
    '''     shuzhuWWW(0) = "100"
    '''     SIEMENS_PLC_butWrite("V", "1000", "1", "W_INT16", shuzhuWWW)

    Protected Sub SIEMENS_PLC_butWrite(ByVal WriteMry As String, ByVal WriteAdd As String, ByVal WriteCnt As String, ByVal WriteType As String, ByVal temp() As String)
        Dim ScanRet As Short
        Dim i As Short
        Dim WD() As Object
        Dim K As Integer
        Dim J As Integer
        If Not EntLink Then
            MsgBox("还未与PLC建立联接！")
            Exit Sub
        End If
        ReDim WD(Val(WriteCnt) - 1)

        For i = 0 To UBound(WD) Step 1
            If i > UBound(temp) Then
                WD(i) = 0
            Else
                WD(i) = Trim(temp(i))
            End If
        Next i

        If WriteType = "W_INT16" Then
            K = 0
        ElseIf WriteType = "W_UINT16" Then
            K = 1
        ElseIf WriteType = "D_DINT32" Then
            K = 2
        ElseIf WriteType = "D_HEX32" Then
            K = 3
        ElseIf WriteType = "D_REAL32" Then
            K = 4
        ElseIf WriteType = "W_BIN16" Then
            K = 5
        ElseIf WriteType = "B_CHAR8" Then
            K = 6
        ElseIf WriteType = "B_BYTE8" Then
            K = 7
        End If
        Dim var1 As Integer = K + 1
        Dim typ As WinTcpS7_Smart.PlcClient.DataType = var1

        If WriteMry = "I" Then
            J = 1
        ElseIf WriteMry = "Q" Then
            J = 2
        ElseIf WriteMry = "M" Then
            J = 3
        ElseIf WriteMry = "V" Then
            J = 4
        End If
        Select Case J
            Case 1 : ScanRet = PLC.CmdWrite(Handle1, WinTcpS7_Smart.PlcClient.PlcMemory.DI, typ, Val(WriteAdd), Val(WriteCnt), WD)
            Case 2 : ScanRet = PLC.CmdWrite(Handle1, WinTcpS7_Smart.PlcClient.PlcMemory.DQ, typ, Val(WriteAdd), Val(WriteCnt), WD)
            Case 3 : ScanRet = PLC.CmdWrite(Handle1, WinTcpS7_Smart.PlcClient.PlcMemory.MR, typ, Val(WriteAdd), Val(WriteCnt), WD)
            Case 4 : ScanRet = PLC.CmdWrite(Handle1, WinTcpS7_Smart.PlcClient.PlcMemory.DR, typ, Val(WriteAdd), Val(WriteCnt), WD)
        End Select
    End Sub

#End Region

#Region "三菱plc通讯"""

    Dim melsecMc = New MelsecMcNet            '("192.168.1.55", "1026")

    Protected Sub Sanlin_PLC_Communications_link()
        '连接对象
        Try
            melsecMc = New MelsecMcNet("192.168.1.55", "1026")
            Dim connect As OperateResult = melsecMc.ConnectServer()
            If connect.IsSuccess Then
                AppendInfoToTextBox("三菱PLC连接成功,端口1026")
            Else
                AppendInfoToTextBox("三菱PLC连接失败,端口1026")
            End If
        Catch ex As Exception
            Timer_QZCS.Enabled = False
            MessageBox.Show(ex.Message)
        End Try
    End Sub

    Protected Sub Close_connectPLC()               ''''断开连接
        melsecMc.ConnectClose()
    End Sub

    ''' <summary>
    ''' 向三菱PLC中对应地址写入数据
    ''' 写入数据必须死>0的整数
    ''' </summary>
    ''' <param name="WriteId"></param>
    ''' <param name="WriteCnt"></param>
    ''' <param name="WriteAdd"></param>
    ''' <param name="WriteDate"></param>
    ''' <remarks></remarks>
    Private Sub WriteDeviceRandom_Torsion(ByVal WriteAdd As String, ByVal WriteDate As String)
        Try
            'melsecMc = New MelsecMcNet(WriteId, WriteCnt)
            'Sanlin_PLC_Communications_link()
            'waitstandby(100)
            Dim reLink As Integer = 0
aa:
            writeResultRender(melsecMc.Write(WriteAdd, Short.Parse(WriteDate)), WriteAdd)
            If PLCFlag = False And reLink < 3 Then
                Close_connectPLC()               ''''断开连接
                waitstandby(200)
                Sanlin_PLC_Communications_link()
                reLink += 1
                GoTo aa
            End If
            'Close_connectPLC()               ''''断开连接
        Catch ex As Exception
            MessageBox.Show(ex.Message)
        End Try
    End Sub

    ''   向三菱PLC读取数据
    ''例子：Angle2 = ReadDeviceRandom_Date("192.168.1.55", "1026", "D933")
    Public Function ReadDeviceRandom_Date(ByVal WriteAdd As String)
        Dim Read_date As String
        Try
            'melsecMc = New MelsecMcNet(WriteId, WriteCnt)
            'Sanlin_PLC_Communications_link()
            'waitstandby(100)
            'Read_date = readResultRender(Of Short)(melsecMc.ReadInt16(WriteAdd), WriteAdd)
            Dim reLink As Integer = 0
aa:
            Read_date = readResultRender(Of Integer)(melsecMc.ReadInt32(WriteAdd), WriteAdd)
            If PLCFlag = False And reLink < 3 Then
                Close_connectPLC()               ''''断开连接
                waitstandby(200)
                Sanlin_PLC_Communications_link()
                reLink += 1
                GoTo aa
            End If
            Return Read_date
        Catch ex As Exception
            Timer_QZCS.Enabled = False
            MessageBox.Show(ex.Message)
        End Try
    End Function

    Public Function ReadInt16(ByVal WriteAdd As String)
        Dim Read_date As String
        Try
            'melsecMc = New MelsecMcNet(WriteId, WriteCnt)
            'Sanlin_PLC_Communications_link()
            'waitstandby(100)
            'Read_date = readResultRender(Of Short)(melsecMc.ReadInt16(WriteAdd), WriteAdd)
            Dim reLink As Integer = 0
aa:
            Read_date = readResultRender(Of Short)(melsecMc.ReadInt16(WriteAdd), WriteAdd)
            If PLCFlag = False And reLink < 3 Then
                Close_connectPLC()               ''''断开连接
                waitstandby(200)
                Sanlin_PLC_Communications_link()
                reLink += 1
                GoTo aa
            End If
            Return Read_date
        Catch ex As Exception
            Timer_QZCS.Enabled = False
            MessageBox.Show(ex.Message)
        End Try
    End Function

    Private Function ReadPLCBool(Of T)(ByVal result As OperateResult(Of T)) As Boolean
        Dim bool As Boolean = False
        Try
            Dim isSuccess As Boolean = result.IsSuccess
            If isSuccess Then
                PLCFlag = True
                bool = Convert.ToBoolean(result.Content)
            Else
                PLCFlag = False
                Timer_QZCS.Enabled = False
            End If
        Catch ex As Exception
            AddErrMsgToTextBox(ex.Message.ToString())
        End Try
        Return bool

    End Function

    Private Function ReadPLCM() As ReadPLC
        Dim bol As Boolean = False
        Dim read As ReadPLC = New ReadPLC
        read.Emergency = False
        read.Light = False
        Try
            read.Light = ReadPLCBool(Of Boolean)(melsecMc.ReadBool("Y6")) '门开关以及光栅
            read.Emergency = ReadPLCBool(Of Boolean)(melsecMc.ReadBool("M231")) '机器人报警
            read.ERRORP = ReadPLCBool(Of Boolean)(melsecMc.ReadBool("M233")) '锁附伺服报警
            read.ERRORX = ReadPLCBool(Of Boolean)(melsecMc.ReadBool("M232")) '旋转伺服报警
            read.ERRORPD = ReadPLCBool(Of Boolean)(melsecMc.ReadBool("M234"))  '皮带驱动器报警
            read.ERRORZ = ReadPLCBool(Of Boolean)(melsecMc.ReadBool("M235"))  'z轴报警
        Catch ex As Exception
            AddErrMsgToTextBox(ex.Message.ToString())
        End Try
        Return read
    End Function

    Public Class ReadPLC
        Public Light As Boolean '门开关以及光栅
        Public Emergency As Boolean '机器人报警
        Public ERRORP As Boolean '锁附伺服报警
        Public ERRORX As Boolean '旋转伺服报警
        Public ERRORPD As Boolean '皮带驱动器报警
        Public ERRORZ As Boolean 'z轴报警
    End Class

    Private Sub writeResultRender(ByVal result As OperateResult, ByVal address As String)

        Dim isSuccess As Boolean = result.IsSuccess
        If isSuccess Then
            PLCFlag = True
            AppendInfoToTextBox(DateTime.Now.ToString("[HH:mm:ss] ") + "[" + address + "] 写入成功")
        Else
            PLCFlag = False
            AppendInfoToTextBox(DateTime.Now.ToString("[HH:mm:ss] ") & "[" & address & "] 写入失败" & Environment.NewLine & "原因：" & result.ToMessageShowString())
        End If
    End Sub

    Public Function readResultRender(Of T)(ByVal result As OperateResult(Of T), ByVal address As String)
        Dim Date_READ As String = ""
        Dim isSuccess As Boolean = result.IsSuccess
        If isSuccess Then
            PLCFlag = True
            Date_READ = Format(result.Content, 0)
        Else
            PLCFlag = False
            Timer_QZCS.Enabled = False
            'MessageBox.Show(DateTime.Now.ToString("[HH:mm:ss] ") & "[" & address & "] 读取失败" & Environment.NewLine & "原因：" & result.ToMessageShowString())
        End If
        Return Date_READ
    End Function

#End Region

    Private Sub Timer4_Tick(sender As Object, e As EventArgs) Handles Timer4.Tick
        Dim allPort() As String = SerialPort.GetPortNames()
        Dim flag As Boolean = False
        For i As Integer = 0 To allPort.Length - 1
            If allPort(i) = "COM2" Then
                flag = True
                Exit For
            End If
        Next
        If flag = False Then
            AppendInfoToTextBox("COM2串口扫码器断开连接")
            COM2_ZT.Text = "断开"
            COM2_ZT.BackColor = Color.Red
            Timer4.Enabled = False
        End If
    End Sub

    Private Sub Button2_Click_2(sender As Object, e As EventArgs) Handles Button2.Click
        Try
            Threading.Thread.Sleep(2000)
            If SP1.IsOpen Then
                SP1.Close()
            End If
            SP1.PortName = "COM1"
            SP1.BaudRate = 9600
            SP1.DataBits = 8
            SP1.StopBits = IO.Ports.StopBits.One
            SP1.Open()
            If SP1.IsOpen Then
                AppendInfoToTextBox("COM2串口扫码器重新连接OK")
                COM2_ZT.Text = "连接"
                COM2_ZT.BackColor = Color.Lime
                Timer4.Enabled = True
            End If
        Catch ex As Exception
            MsgBox(ex.Message.ToString & ex.StackTrace.ToString)
        End Try

    End Sub

    Private Sub CallRobotProgram(p1 As String)
        Throw New NotImplementedException
    End Sub

    Private Sub WWWWWToolStripMenuItem_Click(sender As Object, e As EventArgs)
        Try
            SendDataAndRecvice("STEP1", "192.168.1.120", "2015")
        Catch ex As Exception
            MsgBox(1111)
        End Try

    End Sub

    Private Sub DogCheck_Tick(sender As Object, e As EventArgs) Handles DogCheck.Tick
        CheckDog()
    End Sub

    Public Function CheckDog() As Boolean
        Try
            Dim iret As UInteger = 0
            Dim Count As Integer = 0
            Dim pDongleInfo As DONGLE_INFO = New DONGLE_INFO()
            Dim hDongle As UInteger = 0
            iret = JDKey_Enum(pDongleInfo, Count)
            If iret <> 0 Then
                FlagNum1 += 1
                If FlagNum1 = CheckNum Then
                    Application.Exit()
                End If
                If CheckNum - FlagNum1 = 1 Then
                    ShowMessageBoxTimeout("未检测到任何加密狗,剩余重试次数：" & CheckNum - FlagNum1 & vbCrLf & "软件即将自动关闭.....", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error, 3000)
                Else
                    ShowMessageBoxTimeout("未检测到任何加密狗,剩余重试次数：" & CheckNum - FlagNum1, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error, 3000)
                End If

                Return False
            End If
            Dim HexStr As String = Hex(pDongleInfo.m_ProductID)
            Dim MD5Str As String = MD5Encrypt(HexStr)
            If MD5Str <> mjm Then
                FlagNum2 += 1
                If FlagNum2 = CheckNum Then
                    Application.Exit()
                End If

                If CheckNum - FlagNum2 = 1 Then
                    ShowMessageBoxTimeout("请插入指定加密狗,剩余重试次数：" & CheckNum - FlagNum2 & vbCrLf & "软件即将自动关闭.....", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error, 3000)
                Else
                    ShowMessageBoxTimeout("请插入指定加密狗,剩余重试次数：" & CheckNum - FlagNum2, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error, 3000)
                End If
                Return False
            End If
            FlagNum1 = 0
            FlagNum2 = 0
            'iret = JDKey_Open(hDongle, "0B13463A", 0)
            'If iret <> JDKEY_DEFINE.DONGLE_SUCCESS Then
            '    If FlagNum2 = CheckNum Then
            '        Application.Exit()
            '    End If
            '    FlagNum2 += 1
            '    MessageBox.Show("请插入指定加密狗", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error)
            '    Return False
            'End If
            'FlagNum1 = 0
            'FlagNum2 = 0
            'iret = JDKey_Close(hDongle)
        Catch ex As Exception
            MessageBox.Show(ex.Message.ToString & ex.StackTrace.ToString, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try
        Return True
    End Function

#Region "查询生产报表"""

    Private Sub SaveDeviation(ByVal dateTime As String, ByVal proCount As String, ByVal XH As String, ByVal NL As String, ByVal ScrewTime As String, ByVal ScrewQS As String, ByVal result As String)

        Test_Date_deleted() '''''''''''删除过期生产数据
        Try
            Dim sql As String = "insert into Test_Date(日期,产品条码,产品型号,线别,站别,状态,循环时间) values(" & "'" & dateTime & "'" & "," & "'" & proCount & "'" & "," & "'" & XH & "'" & "," & "'" & NL & "'" & "," & "'" & ScrewTime & "'" & "," & "'" & ScrewQS & "'" & "," & "'" & result & "'" & ")"
            'Dim cnStr As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source= Tool\Test_Date.accdb;Persist Security Info=False"
            'Dim cn As OleDbConnection = New OleDbConnection(cnStr)
            'cn.Open()
            'Dim dc As OleDbCommand = New OleDbCommand(sql, cn)
            'Dim i As Integer = dc.ExecuteNonQuery()
            'cn.Close()
            HandleMysql(sql)
        Catch ex As Exception
            MsgBox("SaveDeviation:" & ex.Message.ToString)
        End Try
    End Sub

    Private Sub ONECheck_Button_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ONECheck_Button.Click
        'Test_Date_deleted()
        If DateTimePicker3.Value > DateTimePicker4.Value Then
            MsgBox("查询开始时间大于结束时间！")
        Else
            Dim sql As String = "select * from Test_Date where 日期 >=" & "'" & Format(DateTimePicker3.Value, "yyyy-MM-dd HH:mm:ss") & "'" & "and " & "日期 <=" & "'" & Format(DateTimePicker4.Value, "yyyy-MM-dd HH:mm:ss") & "'"
            Dim sql1 As String = sql & "and " & "状态 = 'NG'"
            Dim ds As DataSet = SearchMysql(sql)
            Dim ds1 As DataSet = SearchMysql(sql1)
            'DataGridView2.AutoGenerateColumns = True
            DataGridView3.DataSource = ds.Tables(0)  '''''''''''''TextBox8.Text = DataGridView3.Rows.Count

            TextBox8.Text = ds.Tables(0).Rows.Count
            TextBox9.Text = ds1.Tables(0).Rows.Count
            Dim LN As Double = 100 * (1 - Val(TextBox9.Text) / Val(TextBox8.Text))
            TextBox10.Text = Format(LN, "0.00") & "%"
        End If
    End Sub

    'Public Function SearchDB3(ByVal sql As String) As DataSet
    '    Try
    '        Dim cnStr As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source= Tool\Test_Date.accdb;Persist Security Info=False"
    '        Dim cn As OleDbConnection = New OleDbConnection(cnStr)
    '        Dim da As OleDbDataAdapter = New OleDbDataAdapter(sql, cn)
    '        Dim ds As DataSet = New DataSet
    '        da.Fill(ds, "table")
    '        Return ds
    '    Catch ex As Exception
    '        MsgBox("SearchDB3:" & ex.Message.ToString)
    '    End Try
    'End Function
    Private Sub AllCheck_Button_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles AllCheck_Button.Click
        Dim sql As String = "select * from Test_Date order by ID"
        Dim sql1 As String = "select * from Test_Date where 状态 = 'NG'"
        Dim ds As DataSet = SearchMysql(sql)
        Dim ds1 As DataSet = SearchMysql(sql1)
        DataGridView3.DataSource = ds.Tables(0)

        TextBox8.Text = ds.Tables(0).Rows.Count '''''''''''''TextBox8.Text = DataGridView3.Rows.Count
        TextBox9.Text = ds1.Tables(0).Rows.Count
        Dim LN As Double = 100 * (1 - Val(TextBox9.Text) / Val(TextBox8.Text))
        TextBox10.Text = Format(LN, "0.00") & "%"
    End Sub

    Private Sub Out_Button10_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Out_Button10.Click
        ExportExcel(DataGridView3, "生产报表")
    End Sub

    Private Sub Test_Date_deleted()
        Try
            Dim dt As DateTime = DateTime.Now
            Dim dt2 As DateTime = dt.AddYears(-1) '减去一年
            Dim dt3 As DateTime = dt.AddDays(-30) '减去30天

            Dim sql As String = "delete from  Test_Date where 日期 <" & "'" & Format(dt3, "yyyy-MM-dd HH:mm:ss") & "'"
            HandleMysql(sql)
        Catch ex As Exception
            'Error_report_storage(Format(DateAndTime.Now, "yyyy-MM-dd HH:mm:ss"), Todaycount.PassCount + 1, Chanpin, ex.Message.ToString, "待分析", "咨询生产厂商", "软件故障")   '''信息写入数据库中
            AppendInfoToTextBox(ex.Message.ToString)
            MsgBox(ex.Message.ToString & vbCrLf & ex.StackTrace.ToString)
        End Try

    End Sub

#End Region

#Region "报表execl导出"""

    'Public Function ExportExcel(ByVal dgv As DataGridView) As Boolean
    Public Function ExportExcel(ByVal dgv As DataGridView, ByVal folder As String) As Boolean
        Try
            If dgv.Rows.Count > 1 Then
                If dgv.Rows.Count < 1000 Then
                    Dim myExcel As New Microsoft.Office.Interop.Excel.Application
                    myExcel.Application.Workbooks.Add(True)
                    myExcel.Visible = True
                    '导出表头
                    Dim i, j, k As Integer
                    ''''<span style="white-space:pre">	</span>'利用循环，填写表头
                    For k = 0 To dgv.ColumnCount - 1
                        myExcel.Cells(1, k + 1) = dgv.Columns(k).HeaderText
                        myExcel.Cells(1, k + 1).font.bold = True '''''字体为粗体
                        myExcel.Cells(1, k + 1).font.size = 12 '''''字体为12粗体
                    Next
                    '利用循环嵌套，将datagridview内容放到导出为excel表格
                    '这里有两个循环i表示行循环，j为列循环，excel先从行开始循环，excel需要从列开始循环
                    For i = 0 To dgv.Rows.Count - 2
                        For j = 0 To dgv.ColumnCount - 1
                            myExcel.Cells(i + 2, j + 1) = dgv(j, i).Value.ToString
                        Next
                    Next
                    myExcel.Range("A:H").HorizontalAlignment = Microsoft.Office.Interop.Excel.XlVAlign.xlVAlignCenter '''''表格文字居中
                    myExcel.Columns.EntireColumn.AutoFit() '''''列宽自适应

                    Dim openresult As Boolean = Exists(gVisionFailedPath & folder)
                    If openresult = False Then
                        Directory.CreateDirectory(gVisionFailedPath & folder)
                    End If

                    myExcel.ActiveWorkbook.SaveAs(gVisionFailedPath & folder & "/" & Format(DateAndTime.Now, "yyyyMMddHHmmss") & ".xlsx")
                    myExcel.Quit()
                    myExcel = Nothing
                    'myExcel.ActiveWorkbook.SaveAs(Filename:=openresult & "\DEMO1.xls")
                    'myExcel.ActiveWorkbook.SaveAs(Filename:="C:\EXCEL\DEMO1.xls")
                    'myExcel.Workbooks.Close()
                    MsgBox("导出成功")
                Else
                    MsgBox("提示：导出数据过大，无法导出！最大只能导出1000条。")
                End If
            Else
                MsgBox("提示：表格中没有数据记录，不能进行导出数据！")
            End If
            Return True
        Catch ex As Exception
            'Error_report_storage(Format(DateAndTime.Now, "yyyy-MM-dd HH:mm:ss"), ex.Message.ToString, "待分析", "咨询生产厂商", "软件故障")   '''信息写入数据库中
            AppendInfoToTextBox(ex.Message.ToString)
            MsgBox(ex.Message.ToString & vbCrLf & ex.StackTrace.ToString)
        End Try
    End Function

#End Region

#Region "查询付锁报表"""

    Private Sub ScrewtoAccess(ByVal sn As String, ByVal dateTime As String, ByVal proCount As String, ByVal XH As String, ByVal NL As String, ByVal FG As String, ByVal ScrewTime As String, ByVal ScrewQS As String, ByVal result As String)
        Try
            Look_screw_deleted() '''''''''''''删除过期锁付数据

            Dim sql As String = "insert into Look_screw(SN,日期,当日数量,产品型号,锁附扭力,浮高,时间,站别,结果) values(" & "'" & sn & "'" & "," & "'" & dateTime & "'" & "," & "'" & proCount & "'" & "," & "'" & XH & "'" & "," & "'" & NL & "'" & "," & "'" & FG & "'" & "," & "'" & ScrewTime & "'" & "," & "'" & ScrewQS & "'" & "," & "'" & result & "'" & ")"
            HandleMysql(sql)
        Catch ex As Exception
            AppendInfoToTextBox("ScrewtoAccess:" & ex.Message.ToString & ex.StackTrace.ToString)
        End Try
    End Sub

    Private Sub LoadAccess1()
        Try
            Dim sql As String = "select * from Look_screw order by ID"
            Dim sql1 As String = "select * from Look_screw where 结果 = 'NG'"
            Dim ds As DataSet = SearchMysql(sql)
            Dim ds1 As DataSet = SearchMysql(sql1)
            DataGridView2.DataSource = ds.Tables(0)

            TextBox13.Text = ds.Tables(0).Rows.Count
            TextBox12.Text = ds1.Tables(0).Rows.Count
            Dim LN As Double = 100 * (1 - Val(TextBox12.Text) / Val(TextBox13.Text))
            TextBox11.Text = Format(LN, "0.00") & "%"
        Catch ex As Exception
            AppendInfoToTextBox("LoadAccess1:" & ex.Message.ToString & ex.StackTrace.ToString)
        End Try

    End Sub

    Private Sub Button6_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button6.Click

        If DateTimePicker1.Value > DateTimePicker2.Value Then
            MsgBox("查询开始时间大于结束时间！")
        Else
            Dim sql As String = "select * from Look_screw where 日期 >=" & "'" & Format(DateTimePicker1.Value, "yyyy-MM-dd HH:mm:ss") & "'" & "and " & "日期 <=" & "'" & Format(DateTimePicker2.Value, "yyyy-MM-dd HH:mm:ss") & "'"
            Dim sql1 As String = sql & "and " & "结果 = 'NG'"
            Dim ds As DataSet = SearchMysql(sql)
            Dim ds1 As DataSet = SearchMysql(sql1)
            'DataGridView2.AutoGenerateColumns = True
            DataGridView2.DataSource = ds.Tables(0)

            TextBox13.Text = ds.Tables(0).Rows.Count
            TextBox12.Text = ds1.Tables(0).Rows.Count
            Dim LN As Double = 100 * (1 - Val(TextBox12.Text) / Val(TextBox13.Text))
            TextBox11.Text = Format(LN, "0.00") & "%"

        End If
    End Sub

    'Public Function SearchDB2(ByVal sql As String) As DataSet
    '    Try
    '        Dim cnStr As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source= Tool\Look_screw.accdb;Persist Security Info=False"
    '        Dim cn As OleDbConnection = New OleDbConnection(cnStr)
    '        Dim da As OleDbDataAdapter = New OleDbDataAdapter(sql, cn)
    '        Dim ds As DataSet = New DataSet
    '        da.Fill(ds, "table")
    '        Return ds
    '    Catch ex As Exception
    '        MsgBox("SearchDB:" & ex.Message.ToString)
    '    End Try
    'End Function
    'Public Function HandleDB2(ByVal sql As String) As Integer
    '    Try
    '        Dim cnStr As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source= Tool\Look_screw.accdb;Persist Security Info=False"
    '        Dim cn As OleDbConnection = New OleDbConnection(cnStr)
    '        cn.Open()
    '        Dim dc As OleDbCommand = New OleDbCommand(sql, cn)
    '        Dim i As Integer = dc.ExecuteNonQuery()
    '        cn.Close()
    '        Return i
    '    Catch ex As Exception
    '        MsgBox("HandleDB:" & ex.Message.ToString)
    '    End Try
    'End Function

    Private Sub Button7_Click_1(ByVal sender As Object, ByVal e As EventArgs) Handles Button7.Click
        LoadAccess1()
    End Sub

    Private Sub Button8_Click_1(ByVal sender As Object, ByVal e As EventArgs) Handles Button8.Click
        ExportExcel(DataGridView2, "锁付报表")
    End Sub

    Private Sub Look_screw_deleted()
        Try
            Dim dt As DateTime = DateTime.Now
            Dim dt2 As DateTime = dt.AddYears(-1) '减去一年
            Dim dt3 As DateTime = dt.AddDays(-30) '减去30天

            'Dim cnStr As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source= Tool\Look_screw.accdb;Persist Security Info=False"
            Dim sql As String = "delete from  Look_screw where 日期 <" & "'" & Format(dt3, "yyyy-MM-dd HH:mm:ss") & "'"
            HandleMysql(sql)
            'Dim myconnn As New OleDb.OleDbConnection
            'Dim mycommandn As New OleDb.OleDbCommand
            'myconnn.ConnectionString = cnStr
            'myconnn.Open()
            'mycommandn.Connection = myconnn
            'mycommandn.CommandText = sql
            'mycommandn.CommandType = CommandType.Text
            'mycommandn.ExecuteNonQuery()
            'myconnn.Close()
        Catch ex As Exception
            'Error_report_storage(Format(DateAndTime.Now, "yyyy-MM-dd HH:mm:ss"), Todaycount.PassCount + 1, Chanpin, ex.Message.ToString, "待分析", "咨询生产厂商", "软件故障")   '''信息写入数据库中
            AppendInfoToTextBox(ex.Message.ToString)
            MsgBox(ex.Message.ToString & vbCrLf & ex.StackTrace.ToString)
        End Try

    End Sub

#End Region

    Private Sub Timer_DL_Tick(sender As Object, e As EventArgs) Handles Timer_DL.Tick
        If gPriority <> 0 Then
            If MouseMove_X = MouseMove2_X And MouseMove_Y = MouseMove2_Y Then
                AppendInfoToTextBox("达到设定时间，自动退出登录")
                gPriority = 0
                DataByPCS.OperatorID = ""
                TextBox_OPID.Text = "未登录"
                TextBox_OPID.BackColor = Color.WhiteSmoke
                FrmAdmin.EnableMenu()
            End If
        End If
        MouseMove2_X = System.Windows.Forms.Cursor.Position.X
        MouseMove2_Y = System.Windows.Forms.Cursor.Position.Y
    End Sub

    Private Sub Timer_SMSB_Tick(sender As Object, e As EventArgs) Handles Timer_SMSB.Tick
        MouseMove_X = System.Windows.Forms.Cursor.Position.X
        MouseMove_Y = System.Windows.Forms.Cursor.Position.Y
    End Sub

    Private Sub Timer_QZCS_Tick(sender As Object, e As EventArgs) Handles Timer_QZCS.Tick
        Try
            TextBox_Sycs.Text = ReadDeviceRandom_Date("D892")
            TextBox_Setcs.Text = ReadDeviceRandom_Date("D896")
            If QIZTOU <> TextBox_Setcs.Text Then
                If QIZTOU1 = False Then
                    QIZTOU = TextBox_Setcs.Text
                    QIZTOU1 = True
                Else
                    QIZTOU = TextBox_Setcs.Text

                End If
            End If
            If TextBox_Sycs.Text = 0 And QIZTOU2 = False Then
                QIZTOU2 = True

            End If
            If TextBox_Sycs.Text <> 0 Then
                QIZTOU2 = False
            End If
        Catch ex As Exception
            AppendInfoToTextBox("定时器PLC起子头数据读取出错，请确认网络后，重启登录！")
            Timer_QZCS.Enabled = False
        End Try
    End Sub

    ''' <summary>
    ''' SN扫入后的处理程序
    ''' </summary>
    ''' <param name="Str"></param>
    ''' <remarks></remarks>
    Private Sub SNInputProcess(ByVal Str As String)
        If Str <> "" Then
            Dim UseSN As String = Str.Split(",")(0)
            If UseSN <> "" Then
                REPLY_MES = AGMES(UseSN)
                AppendInfoToTextBox("MES返回信息：" & REPLY_MES & vbCrLf)
            Else
                AppendInfoToTextBox("未扫到条码！" & vbCrLf)
            End If
        End If
    End Sub

    Public Function AGMES(ByVal s As String) As String
        Dim a As String = ""
        Try
            Dim sw As IO.StreamWriter
            Dim sr As IO.StreamReader
            Dim p As System.Diagnostics.Process = New System.Diagnostics.Process
            Dim psI As System.Diagnostics.ProcessStartInfo = New System.Diagnostics.ProcessStartInfo("C:\Windows\System32\cmd.exe")
            psI.UseShellExecute = False
            psI.RedirectStandardInput = True
            psI.RedirectStandardOutput = True
            psI.RedirectStandardError = False
            psI.CreateNoWindow = True
            p.StartInfo = psI
            p.StartInfo.UseShellExecute = False
            p.Start()
            sw = p.StandardInput
            sr = p.StandardOutput
            sw.WriteLine("cd BMS" & vbCrLf)
            Dim STR As String = "bms_tool.exe --action=" & Chr(34) & "query-jobinfo" & Chr(34) & " --mgt=" & Chr(34) & s & Chr(34) & " --key=" & Chr(34) & "model" & Chr(34) & vbCr
            AppendInfoToTextBox("发送获取标签信息：" & STR)
            sw.WriteLine(STR)
            Dim MYSTREAMR As IO.StreamReader = p.StandardOutput
            For i As Integer = 0 To 8
                a = MYSTREAMR.ReadLine
            Next
            sr.Close()
            Return a
        Catch ex As Exception
            MsgBox(ex.Message.ToString)
            Return a
        End Try
    End Function

    ''' <summary>
    ''' ScanSNAndMESRequest
    ''' </summary>
    ''' <param name="SN"></param>
    ''' <remarks></remarks>
    Public Function ScanSNAndMESRequest(ByVal SN As String) As Boolean
        Try
            If Can_Barcode = False Or SN = Input Then
                Return False
            End If
            AppendInfoToTextBox("接收扫码枪数据：" & SN)
            ''''''''SN判断规则''''''''''''''''
            'If SN(0) = JQStart Then
            'Else
            '    AppendInfoToTextBox("SN不符" + vbCrLf)
            '    Return False
            'End If
            ' '''''''''''''''''''''''''''''''
            'If SN.Length < JQLength Or newset(0) = False Then 'newset(0)启用扫码切模板
            '    AppendInfoToTextBox("SN条码长度与设置不符" + vbCrLf)
            '    Return False
            'End If
            Dim time As DateTime = DateTime.Now
            Dim curProd As New ProdInfo
            If SN <> Input Then
                Can_Barcode = False '禁止读码
                AppendInfoToTextBox("SN:" & SN & vbCrLf & "Length:" & SN.Length)
                Input = SN
                Dim SFData As String = MES_BaseDataRequest(SN) ''''接收MES回传信息
                AppendInfoToTextBox("接收MES回传Base信息：" & SFData)
                If SFData <> "" Then
                    '''''''''''MES回传模板名'''''''''''''''''''''''''''''''''''''''''''''''''''''''
                    Dim mes As NCHQUPMES = New NCHQUPMES

                    mes = Method.JsonToObject(Of NCHQUPMES)(SFData)

                    If mes.HEAD.H_RET = "00001" Then
                        curProd.sn = SN
                        curProd.G_COLOR = mes.MAIN.G_COLOR
                        curProd.model_name = mes.MAIN.G_MODEL & "_" & mes.MAIN.G_COLOR
                        Dim stime As String = Round((DateTime.Now.Ticks - time.Ticks) / 10000, 1) & "ms"
                        AppendInfoToTextBox(SN & "MES请求耗时:" & stime)
                    Else
                        AppendInfoToTextBox(SN & "MES请求回传Fail")
                    End If

                    'H_RET = getJsonKeyValue("H_RET", SFData)
                    'If H_RET = "00001" Then
                    '    curProd.sn = SN
                    '    curProd.G_COLOR = getJsonKeyValue1("G_COLOR", SFData)
                    '    curProd.model_name = getJsonKeyValue1("G_MODEL", SFData) & "_" & curProd.G_COLOR
                    '    Dim stime As String = Round((DateTime.Now.Ticks - time.Ticks) / 10000, 1) & "ms"
                    '    AppendInfoToTextBox(SN & "MES请求耗时:" & stime)
                    'Else
                    '    AppendInfoToTextBox(SN & "MES请求回传Fail")
                    'End If
                    '''''''''''本地绑定条码模板名''''''''''''''''''''''''''''''''''''''''''''''''''''''''
                    'curProd.sn = SN
                    'curProd.model_name = 扫码模板管理.query(SN)
                End If
                If SN <> "" Then
                    SN_Queue.Enqueue(curProd)
                    showSNQueueFlag = True
                    Return True
                End If
            End If
        Catch ex As Exception
            AppendInfoToTextBox(ex.Message.ToString() & ex.StackTrace.ToString())
        End Try
        Return False
    End Function

    ''' <summary>
    ''' 展示SN队列的第一第二个元素
    ''' </summary>
    ''' <remarks></remarks>
    Private Sub ShowCurrentSNListQueue()
        Try
            TextBox_SN.Text = ""
            If SN_Queue.Count > 0 Then
                For i As Integer = 0 To SN_Queue.Count - 1
                    Dim Str As String = SN_Queue(i).sn & "," & SN_Queue(i).model_name
                    TextBox_SN.AppendText(Str & vbCrLf)
                Next
            End If
        Catch ex As Exception
            AppendInfoToTextBox(ex.Message.ToString & ex.StackTrace.ToString)
        End Try
    End Sub

    Private Sub sqlChange_Click(sender As Object, e As EventArgs) Handles sqlChange.Click
        AccessToMysql()
    End Sub

    Private Sub Button5_Click(sender As Object, e As EventArgs) Handles Button5.Click
        Try
            Button5.BackColor = Color.Red
            AddProdflag1 = True
        Catch ex As Exception
            MsgBox(ex.Message.ToString)
        End Try
    End Sub

    Private Sub Button9_Click(sender As Object, e As EventArgs) Handles Button9.Click
        Try
            If newset(7) Then
                Dim SN As String = "1232"
                Dim SFData As String = MES_SCADA_FormateDemo(SN) ''''接收MES回传信息
            End If
        Catch ex As Exception
            MsgBox(ex.Message.ToString)
        End Try
    End Sub

    Private Sub Timer2_Tick(sender As Object, e As EventArgs)
        Try
        Catch ex As Exception
            MsgBox(ex.Message.ToString)
        End Try
    End Sub

    Private Sub Button10_Click(sender As Object, e As EventArgs) Handles Button10.Click
        Try
            If MsgBox("是否清空扫码队列？", MsgBoxStyle.YesNo) = MsgBoxResult.Yes Then
                SN_Queue.Clear()
                Input = ""
                SNInputBox.Clear()
                showSNQueueFlag = True
            End If
        Catch ex As Exception

        End Try
    End Sub

    Dim light As Boolean = False
    Dim Emergency As Boolean = False
    Dim ERRORP As Boolean = False
    Dim ERRORX As Boolean = False
    Dim ERRORPD As Boolean = False
    Dim ERRORZ As Boolean = False

    Private Sub TimerLight_Tick(sender As Object, e As EventArgs) Handles TimerLight.Tick
        Try
            Dim read As ReadPLC = New ReadPLC
            read = ReadPLCM()
            If read.Light And light Then
                AddErrMsgToTextBox("错误信息:安全门或光栅打开")
                light = False
            ElseIf read.Light = False Then
                light = True
            End If
            If read.Emergency And Emergency Then
                AddErrMsgToTextBox("错误信息:急停按钮按下")
                Emergency = False
            ElseIf read.Emergency = False Then
                Emergency = True
            End If
            If read.ERRORP And ERRORP Then
                AddErrMsgToTextBox("错误信息:锁附伺服驱动器报警")
                ERRORP = False
            ElseIf read.ERRORP = False Then
                ERRORP = True
            End If
            If read.ERRORX And ERRORX Then
                AddErrMsgToTextBox("错误信息:旋转伺服驱动器报警")
                ERRORX = False
            ElseIf read.ERRORX = False Then
                ERRORX = True
            End If
            If read.ERRORPD And ERRORPD Then
                AddErrMsgToTextBox("错误信息:皮带驱动器报警")
                ERRORPD = False
            ElseIf read.ERRORPD = False Then
                ERRORPD = True
            End If
            If read.ERRORZ And ERRORZ Then
                AddErrMsgToTextBox("错误信息:Z轴驱动器报警")
                ERRORZ = False
            ElseIf read.ERRORZ = False Then
                ERRORZ = True
            End If
        Catch ex As Exception
            AddErrMsgToTextBox(ex.Message.ToString)
        End Try
    End Sub

    Private Sub TextBox15_KeyDown_1(sender As Object, e As KeyEventArgs) Handles TextBox15.KeyDown
        Try
            If e.KeyCode = Keys.Enter Then
                SNInputScan_screw(TextBox15.Text)
                TextBox15.Text = ""
            End If
        Catch ex As Exception
            AppendInfoToTextBox("SNInputBox:" & ex.Message.ToString)
            TextBox15.Text = ""
        End Try
    End Sub

    ''' <summary>
    ''' SN扫入后的处理程序
    ''' </summary>
    ''' <param name="Str"></param>
    ''' <remarks></remarks>
    Private Sub SNInputScan_screw(ByVal Str As String)
        Dim Feeder As String = ""
        If Str <> "" Then
            Dim UseSN As String = Str.Split(",")(0)
            If UseSN <> "" Then
                Dim sql As String = "select * from Scan_screw Where SN='" & UseSN & "' And 模板名称='" & Chanpin & "'"
                Dim ds As DataSet = SearchMysql(sql)
                If ds.Tables(0).Rows.Count > 0 Then
                    Feeder = ds.Tables(0).Rows(0)("供料器号")
                    MsgBox("该料号" & UseSN & "螺丝位于" & Feeder & "号供料器")
                    AppendInfoToTextBox(UseSN & "扫码确认螺丝！" & vbCrLf)
                Else
                    MsgBox("未查询到该螺丝料号，请添加！！！")
                End If
            Else
                AppendInfoToTextBox("未扫到条码！" & vbCrLf)
            End If
        End If
    End Sub

    Private Sub MES设备信息配置ToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles MES设备信息配置ToolStripMenuItem.Click
        Dim frm As New NCHQMES.FrmMesMachineInfo
        frm.Show()
    End Sub

    Private Sub 报警信息设置ToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles 报警信息设置ToolStripMenuItem.Click
        Dim frm1 As New FrmErr
        frm1.ShowDialog()
    End Sub

    Private Sub Timer_deletePath_Tick_1(sender As Object, e As EventArgs) Handles Timer_deletePath.Tick
        Try
            Method.DeletePath(DebugPath & "\log")
            Method.DeletePath(DebugPath & "\Err_log")
            Method.DeletePath(DebugPath & "\MesLog")
        Catch ex As Exception
            AddErrMsgToTextBox("删除文件错误,错误信息{" & ex.Message.ToString() & "}")
        End Try
    End Sub

#Region "定时发送心跳"

    Private MesConectFlag As Boolean

    Private Sub Timer_HeartBeat_Tick(sender As Object, e As EventArgs) Handles Timer_HeartBeat.Tick

        If newset(7) Then
            labMesHeart.Text = "启用MES心跳"
            Try
                Dim str As String = Method.MES_SCADA_Heartbeat()
                If str.Contains("成功") Then
                    labMesHeart.BackColor = Color.Lime
                    MesConectFlag = True
                ElseIf str.Contains("失败") Then
                    labMesHeart.BackColor = Color.Red
                    MesConectFlag = False
                End If
                AppendMESToTextBox(str)
            Catch ex As Exception
                AddErrMsgToTextBox(ex.Message)
                labMesHeart.BackColor = Color.Red
                MesConectFlag = False
            End Try
        Else
            labMesHeart.Text = "未启用MES心跳"
        End If

    End Sub

#End Region

End Class